1.在Java读取Excel会遇到报错 Cannot get a STRING value from a NUMERIC cell我就是遇到了这种坑,这里我来分享心得,希望能帮助到各位小伙伴们!
想看NUMERIC TO TEXT(生成excel)的请看这篇文章 :https://blog.youkuaiyun.com/jiaobuchong/article/details/77513253
在这里给大家说明下原因,是因为在导入Excel时你手动填的数字POI读取的时候默认会把他当做NUMBER来处理,而这时
你又用cell.getStringCellValue()所有会报错。我也是这个问题弄了好半天,终于想到一个通用的办法来解决,通过了解底层
源码来解决问题。请往下看.......

Java代码在读取的时候想要的是字符串:1242532523632,那怎么办?
public static String getCellStringValue(Cell cell) {
if (cell == null) {
return "";
}
CellType type = cell.getCellTypeEnum();
String cellValue;
switch (type) {
case BLANK:
cellValue = "";
break;
case _NONE:
cellValue = "";
break;
case ERROR:
cellValue = "";
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case NUMERIC:
cellValue = NumberToTextConverter.toText(cell.getNumericCellValue());
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
case FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
break;
}
return cellValue;
}
public static void readExcel() throws Exception {
FileInputStream inputStream = new FileInputStream(new File("test.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Cell cell = sheet.getRow(1).getCell(0);
String cellValue = getCellStringValue(cell);
System.out.println(cellValue);
workbook.close();
inputStream.close();
}
public static void main(String[] args) throws Exception {
readExcel();
}
红颜色的可以不用看,在代码中你将cell传入方法中就可以了,直接就拿返回的字符串用。
到了这里就完了,希望此篇文章能帮到大家----------------------------
博客分享了Java读取Excel时遇到报错“Cannot get a STRING value from a NUMERIC cell”的解决心得。原因是导入Excel手动填的数字,POI读取默认当NUMBER处理,用cell.getStringCellValue()会报错,作者通过了解底层源码找到通用解决办法。
508

被折叠的 条评论
为什么被折叠?



