Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve INTEGER values from excel using JAVA

My aim is to read an excel file uisng POI and print the values present in it. If the value is 5 then my output must be 5. but it is returning as 5.0. The below is the code that I have tried.

    FileInputStream fileInputStream = null;
    XSSFSheet xssfResultSheet = null;
    String filePath = "C:\\MyXcel.xlsx";
    fileInputStream = new FileInputStream(new File(filePath));
    XSSFWorkbook workbook = null;
    workbook = new XSSFWorkbook(fileInputStream);
    xssfResultSheet = workbook.getSheet("Sheet1");
    int iRowCount = xssfResultSheet.getLastRowNum();

    for (int i = 1; i <= iRowCount; i++) {
        Row resultRow = xssfResultSheet.getRow(i);
        System.out.println(resultRow.getCell(0));
    }

My Excel has values 1,2,3 but my output is 1.0,2.0,3.0. Instead my output should also be 1,2,3

like image 942
user3387609 Avatar asked Dec 26 '22 12:12

user3387609


1 Answers

Change:

System.out.println(resultRow.getCell(0));

To:

System.out.println(new DataFormatter().formatCellValue(resultRow.getCell(0)));

Explanation:

apache-poi provides for DataFormatter class as utility to leverage the format of the content as it appears on the excel. You can choose custom formats too, a simple example would be (cell is reference to your XSSFCell object):

Excel sheet looks like:

enter image description here

Code:

System.out.println(new DataFormatter().formatCellValue(cell));

The above line would print:

50%
$ 1,200
12/21/14
9886605446

Whereas your normal print would interpret it differently:

0.5
1200.0
21-Dec-2014
9.886605446E9
like image 114
StoopidDonut Avatar answered Dec 28 '22 08:12

StoopidDonut