“Cannot get a STRING value from a NUMERIC cell“——java excel poi 绝地灬酷狼 2024-03-16 18:44 24阅读 0赞 ### 问题: ### Cannot get a STRING value from a NUMERI excel表格里,单元格是数字格式,但却用getStringCellValue()获取,就会报错。 ### 场景分析: ### 这种场景经常出现在提供的excel模板里单元格是文本格式,但用户直接将他的excel里的数据复制进来,文本格式就变成数字格式了。 ### 代码: ### cell.getStringCellValue(); //不推荐使用 String cellValue = new DataFormatter().formatCellValue(cell) //推荐使用 可以简单封装一下: private String getCellValue(Row row, int idx) { return row.getCell(idx) == null ? "" : new DataFormatter().formatCellValue(row.getCell(idx)); } 详情可见: [cell.getStringCellValue()和new DataFormatter().formatCellValue(cell)——java excel poi][cell.getStringCellValue_new DataFormatter_.formatCellValue_cell_java excel poi] 补充: 使用getStringCellValue(),需要先setCellType(),再获取。但此写法已经不推荐使用。 //getRow获取第i行 Row row = sheet.getRow(i); //getCell获取第i列单元格 Cell cell = row.getCell(i); //设置单元格类型 但setCellType方法现在已过期 cell.setCellType(CellType.STRING); //获取具体单元格数据 String cellValue = cell.getStringCellValue(); 推荐: // getRow获取第i行 Row row = sheet.getRow(i); //row.getCell(i)获取第i列 //new DataFormatter().formatCellValue(cell)格式化当前cell的数据为String String cellValue = new DataFormatter().formatCellValue(row.getCell(i)) =======================分割线============================= 文章到此已结束,以下是紫薯布丁 Cannot get a STRING value from a NUMERI cell.getStringCellValue(); //不推荐使用 String cellValue = new DataFormatter().formatCellValue(cell) //推荐使用 private String getCellValue(Row row, int idx) \{ return row.getCell(idx) == null ? "" : new DataFormatter().formatCellValue(row.getCell(idx)); \} //getRow获取第i行 Row row = sheet.getRow(i); //getCell获取第i列单元格 Cell cell = row.getCell(i); //设置单元格类型 但setCellType方法现在已过期 cell.setCellType(CellType.STRING); //获取具体单元格数据 String cellValue = cell.getStringCellValue(); // getRow获取第i行 Row row = sheet.getRow(i); //row.getCell(i)获取第i列 //new DataFormatter().formatCellValue(cell)格式化当前cell的数据为String String cellValue = new DataFormatter().formatCellValue(row.getCell(i)) [cell.getStringCellValue_new DataFormatter_.formatCellValue_cell_java excel poi]: https://globalcoding.blog.csdn.net/article/details/131233438
还没有评论,来说两句吧...