2011-06-03 55 views
1

我使用Apache POI-HSSF处理Excel文件。Apache POI-HSSF:取得小数而不是文本字符串

我的电子表格中有一个单元格,看起来像“115”。我确认它被格式化为“文本”(格式化单元格 - >文本)。

然而,当我在读它作为 row.getCell(0)的ToString()

我得到这个字符串: “115.0”

这是不正确。因为它被明确地格式化为文本,所以我应该得到“115”。我怎样才能得到想要的结果?单元格可以是任何东西,数字或字符,我希望与单元格中的字符串相同。谢谢

回答

2

格式化为文本并不意味着存储为文本,它们是不同的。 Excel已将您的单元存储为一个数字,并且当您向该单元询问POI时,会返回一个数字单元格。

如果你问你回来它是什么类型的细胞,你会发现它的类型CELL_TYPE_NUMERIC,而不是CELL_TYPE_STRING

你可能会想要做的是使用DataFormatter class有你的格式为每个Excel。它会看起来像你期望的。 (如将单元格格式化为货币,百分比等)

+0

谢谢,它的工作 – user783312 2011-06-10 23:40:17

1

您应该调用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; 
} 
相关问题