Cannot get a text value from a numeric cell “Poi”
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
Formatter will work fine in this case.
import org.apache.poi.ss.usermodel.DataFormatter;
FileInputStream fis = new FileInputStream(workbookName);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
DataFormatter formatter = new DataFormatter();
String val = formatter.formatCellValue(sheet.getRow(row).getCell(col));
list.add(val); //Adding value to list
Cell cell = sheet.getRow(i).getCell(0);
cell.setCellType ( Cell.CELL_TYPE_STRING );
String j_username = cell.getStringCellValue();
UPDATE
Ok, as have been said in comments, despite this works it isn't correct method of retrieving data from an Excel's cell.
According to the manual here:
If what you want to do is get a String value for your numeric cell, stop!. This is not the way to do it. Instead, for fetching the string value of a numeric or boolean or date cell, use DataFormatter instead.
And according to the DataFormatter API
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.
So, right way to show numeric cell's value is as following:
DataFormatter formatter = new DataFormatter(); //creating formatter using the default locale
Cell cell = sheet.getRow(i).getCell(0);
String j_username = formatter.formatCellValue(cell); //Returns the formatted value of a cell as a String regardless of the cell type.
use the code cell.setCellType(Cell.CELL_TYPE_STRING);
before reading the string value, Which can help you.
I am using POI version 3.17 Beta1 version,
sure the version compatibility also..