我正在使用 java 6 中的 apache poi 3.17 读取 xlsx 文件。在一个实例中,我有一个值为 123456789011 的单元格。该单元格作为 NUMERIC CellTypeEnum Cell 读入 java。当我使用 DataFormatter 获取单元格的值时,如下所示:
DataFormatter formatter = new DataFormatter(Locale.US);
String strVal = formatter.formatCellValue(cell);
字符串值显示为“1.234567+11”。我需要单元格中的实际值“123456789011”。我怎样才能得到它?
我已经尝试在 Java 中使用 BigDecimal 来转换字符串,但它返回“123456700000”,因为这是它对给定信息所能做的最好的事情;这意味着我需要从实际的单元格对象中获取正确的值。我还尝试使用 cell.getNumericCellValue() 但返回一个双精度值,它的限制太小而无法处理原始值,因此它被检索为“1.234567E11”,它与其他检索方法具有相同的问题。
有没有办法在 xlsx 中输入原始单元格时获取字符串形式的值?我对原始 xlsx 没有任何权力。
谢谢你。
使用 BigDecimal 的 toPlainString() 方法。它接受科学记数法并将其转换为相应的数字字符串值。
我尝试这样做:(我的工作表中的单元格 A1 中有数字 123456789011,单元格类型为 NUMERIC)
Row row = sheet.getRow(0);
Object o = getCellValue(row.getCell(0));
System.out.println(new BigDecimal(o.toString()).toPlainString());
getCellValue 方法是我读取单元格的通用方法:
public Object getCellValue(Cell cell) {
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
case Cell.CELL_TYPE_BOOLEAN:
return cell.getBooleanCellValue();
case Cell.CELL_TYPE_NUMERIC:
return cell.getNumericCellValue();
}
}
return null;
}
希望这有帮助!
请阅读DataFormatter 文档 并了解用于数字和日期格式的各种模式。
这对我有用,我确实检查了单元格类型是否为数字。
DataFormatter dataFormatter = new DataFormatter(Locale.US);
String cellValue = dataFormatter.formatRawCellContents(cell.getNumericCellValue(), 0, "#",true);