异常
在使用POI读取Excel文件内容时,发生了异常,大概意思是不能从一个数值的列获取一个字符串类型的值,报错如下:
使用了getStringCellValue()方法来获取值,POI会判断单元格的类型,如果非字符串类型就会抛出上面的异常。
如下图,读取绿色框中的值不抛异常,读取红色框中值出抛出异常,POI认为这是一个数字。
解决方式一:
解决方法是在读取某单元格时,使用setCellType()方法先将该单元格的类型设置为STRING,代码如下:
//此处省略N行代码 sheet.getRow(6).getCell(6).setCellType(CellType.STRING); String cellValue = sheet.getRow(6).getCell(6).getStringCellValue(); //此处省略N行代码
解决方式二:
Excel中数值类型值在程序中按字符串类型获取
/** * 拿到不同类型单元格中的值 * 1. 字符串: 字符串 * 2. 布尔: toString * 3. 数值(double): 格式化后的字符串 * @param cell 获取的单元格 * @return 单元格中的值 */ private static String getCellValue(Cell cell) { String resultValue = ""; // 判空 if (Objects.isNull(cell)) { return resultValue; } // 拿到单元格类型 int cellType = cell.getCellType(); switch (cellType) { // 字符串类型 case Cell.CELL_TYPE_STRING: resultValue = StringUtils.isEmpty(cell.getStringCellValue()) ? "" : cell.getStringCellValue().trim(); break; // 布尔类型 case Cell.CELL_TYPE_BOOLEAN: resultValue = String.valueOf(cell.getBooleanCellValue()); break; // 数值类型 case Cell.CELL_TYPE_NUMERIC: resultValue = new DecimalFormat("#.######").format(cell.getNumericCellValue()); break; // 取空串 default: break; } return resultValue; }