Cannot get a text value from a numeric cell “Poi”

前端 未结 11 2087
余生分开走
余生分开走 2020-12-07 22:17

I\'m trying to consume data from a spreadsheet in Excel, but always of this error, already tried formatting the worksheet to text and number and still the error persists.

11条回答
  •  无人及你
    2020-12-07 23:09

    As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING) to get the string value of a numeric cell, as you'll loose all the formatting

    Instead, as the javadocs explain, you should use DataFormatter

    What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.

    So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:

     // Create a formatter, do this once
     DataFormatter formatter = new DataFormatter(Locale.US);
    
     .....
    
     for (int i=1; i <= sheet.getLastRowNum(); i++) {
            Row r = sheet.getRow(i);
            if (r == null) { 
               // empty row, skip
            } else {
               String j_username = formatter.formatCellValue(row.getCell(0));
               String j_password =  formatter.formatCellValue(row.getCell(1));
    
               // Use these
            }
     }
    

    The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell

提交回复
热议问题