Setting Cell Datatype at runtime deleting the cell data in apache poi
i have java code to read excel file using apache poi.i have some requirement and i am setting Cell data type to String while reading the cell data at runtime. for ex
before:
cellData.getStringCellValue() --> "Ramki"
after:
cellData.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("The cell data is:开发者_如何转开发 " + cellData.getStringCellValue()); ---> ""
can we change the cell data type at runtime.
i am using apache POI 3.7
please help me on this.
Thanks, Ramki.
If I understand you correctly, what you're after is basically the text of what Excel would display for each cell?
If so, the key class for you will be DataFormatter which does this for you.
If you take a look at the ExcelExtractor class in POI you'll see a fully worked example of doing this.
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() + ")");
}
精彩评论