Get actual cell value of excel cell with POI without defining a datatype

倾然丶 夕夏残阳落幕 提交于 2019-12-20 03:39:46

问题


I catch my cells from an .xls file like this:

cell.getStringCellValue();

But since some of the cells are numeric, I have to do this instead:

                try
                {
                    cells[colIx] = cell.getStringCellValue();
                } catch (IllegalStateException e)
                {
                    cells[colIx] = String.valueOf(cell.getNumericCellValue());
                }

since it's getting a double and then converts it to a string this results in some unwanted operations like:

  • 1 converts into 1.0 (not that kind of a big problem)
  • 16711680 converts to 1.671168E7

How do I solve this and get the actual cell value instead of some converted numbers? Also, all of the cells are defined as default in excel


回答1:


You can use Apache POI DataFormatter's formatCellValue(Cell cell) method as it returns the formatted value of a cell as a String regardless of the cell type.

According to DataFormatter doc -

DataFormatter contains methods for formatting the value stored in an Cell. This can be useful for reports and GUI presentations when you need to display data exactly as it appears in Excel. Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.

Sample code

DataFormatter dataFormatter= new DataFormatter();

// Inside loop
String cellValueStr = dataFormatter.formatCellValue(cell);



回答2:


try using cell.getCellType() as you have

  1. numeric
  2. date
  3. numeric in scientific notation


来源:https://stackoverflow.com/questions/39953678/get-actual-cell-value-of-excel-cell-with-poi-without-defining-a-datatype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!