只要单元格在用户键入数字之前是文本格式,POI 就允许您以字符串的形式获取值。一个关键是,如果在单元格的左上角有一个格式为 Text 的绿色小三角形,那么您将能够检索它的值作为一个字符串(每当看起来像数字的东西被强制转换为文本格式时,绿色三角形就会出现)。如果您有包含数字的文本格式单元格,但 POI 不允许您以字符串的形式获取这些值,那么可以对电子表格数据执行以下操作:
InputStream inp =getClass().getResourceAsStream("filename.xls"));
Workbook wb = WorkbookFactory.create(inp);
DataFormatter objDefaultFormat = new DataFormatter();
FormulaEvaluator objFormulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);
Sheet sheet= wb.getSheetAt(0);
Iterator<Row> objIterator = sheet.rowIterator();
while(objIterator.hasNext()){
Row row = objIterator.next();
Cell cellValue = row.getCell(0);
objFormulaEvaluator.evaluate(cellValue); // This will evaluate the cell, And any type of cell will return string value
String cellValueStr = objDefaultFormat.formatCellValue(cellValue,objFormulaEvaluator);
}
public final class Cell {
private final static DataFormatter FORMATTER = new DataFormatter();
private XSSFCell mCell;
public Cell(@NotNull XSSFCell cell) {
mCell = cell;
if (isFormula()) {
XSSFWorkbook book = mCell.getSheet().getWorkbook();
FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();
mCell = (XSSFCell) evaluator.evaluateInCell(mCell);
}
}
/**
* Get content
*/
public final int getInt() {
return (int) getLong();
}
public final long getLong() {
return Math.round(getDouble());
}
public final double getDouble() {
return mCell.getNumericCellValue();
}
public final String getString() {
if (!isString()) {
return FORMATTER.formatCellValue(mCell);
}
return mCell.getStringCellValue();
}
/**
* Get properties
*/
public final boolean isNumber() {
if (isFormula()) {
return mCell.getCachedFormulaResultType().equals(CellType.NUMERIC);
}
return mCell.getCellType().equals(CellType.NUMERIC);
}
public final boolean isString() {
if (isFormula()) {
return mCell.getCachedFormulaResultType().equals(CellType.STRING);
}
return mCell.getCellType().equals(CellType.STRING);
}
public final boolean isFormula() {
return mCell.getCellType().equals(CellType.FORMULA);
}
/**
* Debug info
*/
@Override
public String toString() {
return getString();
}
}
int type = cell.getCellType();
if(type == 0){
String value = NumberToTextConverter.toText(cell.getNumericCellValue());
}
else{
value = String.valueOf(cell.getStringCellValue());
}