我使用Apache POI-HSSF来处理Excel文件。
我的电子表格中有一个看起来像"115“的单元格。我验证了它的格式是“文本”(格式单元格->文本)。
但是,当我将其读入为row.getCell(0).toString()
我得到这个字符串:"115.0“
这是不正确的。我应该得到"115“,因为它被显式地格式化为文本。怎样才能得到想要的结果?单元格可以是任何东西,可以是数字或字符,我希望在单元格中使用相同的字符串。谢谢
发布于 2011-06-04 14:05:24
格式化为文本并不意味着存储为文本,它们是不同的。Excel已将您的单元格存储为数字,当您向POI请求该单元格时,您将得到一个数值单元格。
如果您询问返回的单元是什么类型,您会发现它的类型是CELL_TYPE_NUMERIC,而不是CELL_TYPE_STRING
您可能想要做的是使用DataFormatter class将您的单元格设置为符合Excel的格式。然后它看起来就像你所期望的那样。(格式为货币、百分比等的单元格也将如此)
发布于 2015-04-16 10:17:33
您应该调用HSSFCell.getCellType()方法来确定其类型。下面是一个处理String或Numeric类型单元格的方法。(您可以轻松添加其他类型。)用于数字的格式将是有效的格式,但不一定与SpreadSheet的格式匹配。(下面将介绍这一点。)
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;
}https://stackoverflow.com/questions/6232207
复制相似问题