开发者

How to get the formatted value of a number for a cell in Apache POI?

开发者 https://www.devze.com 2023-01-17 20:53 出处:网络
I wanted to get the value of a Numeric cell as a simple string. Suppose there the type of cell is numeric with value 90%.

I wanted to get the value of a Numeric cell as a simple string.

Suppose there the type of cell is numeric with value 90%. Now I cannot use cell.getStringCellValue() as it will thro开发者_JAVA百科w exception. I also cannot use cell.getNumericCellValue() as it will return me .9 and not 90%.

I want to store in db which is of type varchar2, so I want the value in string only.

I cannot change the cell type in xls as its the end user job, I have to handle this in code itself.

Also formatter does't work well as there could be different cell types in the xls...dd:mm,dd:mm:ss,formula etc.

All I want is that whatever the cell type is I need to get its value as simple String.


You can force the value to be returned as a String using the methods below

HSSFDataFormatter hdf = new HSSFDataFormatter();
System.out.println (hdf.formatCellValue(mycell));

will return "90%"

The API for this method is at http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html#formatCellValue%28org.apache.poi.ss.usermodel.Cell%29

This works directly even with an HSSFCell

it worked for me even when my Cell is an HSSFCell

i've also tried this cast - which works.

HSSFCell cell1 = (HSSFCell) row1.getCell(2);

HSSFDataFormatter hdf = new HSSFDataFormatter();
System.out.println ("formatted "+ hdf.formatCellValue(cell1));


Try

cell.getRichStringCellValue ().getString();    

Have a look at this example
Here is Doc


The following code is using current apache poi versions of 2021. Now DataFormatter can be used for XSSF (Office Open XML *.xlsx) as well as for HSSF (BIFF *.xls) formats. It should be used together with FormulaEvaluator to get values from formula cells too.

import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;

class ReadExcel {

 public static void main(String[] args) throws Exception {

  Workbook workbook = WorkbookFactory.create(new FileInputStream("Excel.xlsx"));
  //Workbook workbook = WorkbookFactory.create(new FileInputStream("Excel.xls"));

  DataFormatter dataFormatter = new DataFormatter(java.util.Locale.US);
  FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();

  String cellValue = "";

  for (Sheet sheet: workbook) {
   System.out.println(sheet.getSheetName());
   for (Row row : sheet) {
    for (Cell cell : row) {

     cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator);
     System.out.println(cell.getAddress() + ":" + cellValue);
     // do something with cellValue

    }
   }
  }
  workbook.close();
 }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消