我有Java代码读取excel文件使用apache poi。我有一些要求,我正在设置单元格数据类型为字符串,同时在运行时读取单元格数据。
为例: cellData.getStringCellValue() --> "Ramki"
后:cellData.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("The cell data is: " + cellData.getStringCellValue()); ---> ""
可以在运行时更改单元格的数据类型吗?
我正在使用apache POI 3.7
请帮我一下。
谢谢,Ramki .
如果我理解正确的话,你所追求的基本上是Excel将为每个单元格显示的文本?
如果是,关键类将是DataFormatter,它将为您完成这些工作。
如果你看一下POI中的ExcelExtractor类,你会看到一个完整的工作示例。
HSSFCell cell = row.getCell(k);
switch(cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
text.append(cell.getRichStringCellValue().getString());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
text.append(
_formatter.formatCellValue(cell)
);
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
text.append(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
text.append(ErrorEval.getText(cell.getErrorCellValue()));
break;
case HSSFCell.CELL_TYPE_FORMULA:
if(outputCellFormulas) {
text.append(cell.getCellFormula());
} else {
switch(cell.getCachedFormulaResultType()) {
case HSSFCell.CELL_TYPE_STRING:
HSSFRichTextString str = cell.getRichStringCellValue();
if(str != null && str.length() > 0) {
text.append(str.toString());
}
break;
case HSSFCell.CELL_TYPE_NUMERIC:
HSSFCellStyle style = cell.getCellStyle();
if(style == null) {
text.append( cell.getNumericCellValue() );
} else {
text.append(
_formatter.formatRawCellContents(
cell.getNumericCellValue(),
style.getDataFormat(),
style.getDataFormatString()
)
);
}
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
text.append(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
text.append(ErrorEval.getText(cell.getErrorCellValue()));
break;
}
}
break;
default:
throw new RuntimeException("Unexpected cell type (" + cell.getCellType() + ")");
}