【问题标题】:Apache POI-HSSF: Getting Decimal Instead of Text StringApache POI-HSSF:获取十进制而不是文本字符串
【发布时间】:2015-04-16 10:17:33
【问题描述】:
我正在使用 Apache POI-HSSF 处理 Excel 文件。
我的电子表格中有一个看起来像“115”的单元格。我验证它的格式为“文本”(格式单元格 -> 文本)。
但是,当我读到它时
row.getCell(0).toString()
我得到这个字符串:“115.0”
这是不正确的。我应该得到“115”,因为它被明确格式化为文本。我怎样才能得到想要的结果?单元格可以是任何东西,数字或字符,我希望与单元格中的字符串相同。谢谢
【问题讨论】:
标签:
apache
text
decimal
apache-poi
poi-hssf
【解决方案1】:
格式化为文本并不意味着存储为文本,它们是不同的。 Excel 已将您的单元格存储为数字,当您向 POI 询问单元格时,您会得到一个数字单元格。
如果你询问你返回的单元格是什么类型,你会发现它的类型是 CELL_TYPE_NUMERIC 而不是 CELL_TYPE_STRING
您可能想要做的是使用DataFormatter class 让您的单元格按照 Excel 进行格式化。然后它看起来就像你期望的那样。 (单元格也会被格式化为货币、百分比等)
【解决方案2】:
您应该调用 HSSFCell.getCellType() 方法来确定其类型。这是一种处理字符串或数字类型单元格的方法。 (您可以轻松添加其他类型。)用于数字的格式将是有效格式,但不一定与电子表格的格式匹配。 (这将在下面介绍。)
public static String getCellStringValue(final HSSFCell cell) {
int cellType = cell.getCellType();
String value;
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
// Locale is optional here
DataFormatter dataFormatter = new DataFormatter(Locale.US);
value = dataFormatter.formatCellValue(cell);
} else {
// HSSFCell.CELL_TYPE_STRING
value = cell.getStringCellValue();
} // more cell types are possible. Add whatever you need.
return value;
}
该代码不一定会像 Excel 中显示的那样格式化数字。
如果您需要格式与电子表格格式完全匹配,您可以从单元格本身获取格式化程序。为此,您可以使用 DataFormatter 实例创建一个 Format 实例:
public static String getCellStringValue(final HSSFCell cell) {
int cellType = cell.getCellType();
String value;
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
// Locale is optional here
DataFormatter dataFormatter = new DataFormatter(Locale.US);
Format format = dataFormatter.createFormat(cell);
value = format.format(cell.getNumericCellValue());
} else {
// HSSFCell.CELL_TYPE_STRING
value = cell.getStringCellValue();
} // more cell types are possible. Add whatever you need.
return value;
}