使用Apache POI 5.1修改Excel单元格为数值格式的问题求助
问题原因
- 列默认样式不生效:
setDefaultColumnStyle方法仅对之后新插入的单元格生效,已经存在的单元格会保留自身已绑定的样式,不会自动继承列默认样式。 - 设置单元格样式后仍显示文本:你从CSV转Excel时,所有单元格默认存储的是
String类型的内容,就算给单元格套了数值格式,单元格的内容类型还是文本,Excel会判定为「文本格式的数字」,不会自动当做数值渲染。
解决方法
你需要遍历E、F两列所有已存在的单元格,同时修改单元格的内容类型和样式,完整代码示例如下:
FileInputStream fis = new FileInputStream(final_report_name); XSSFWorkbook workBook = new XSSFWorkbook(fis); XSSFSheet new_sheet = workBook.getSheetAt(0); // 创建统一的数值格式样式 XSSFDataFormat format = workBook.createDataFormat(); XSSFCellStyle numberStyle = workBook.createCellStyle(); // 可根据需求调整格式,比如保留2位小数改为"0.00" numberStyle.setDataFormat(format.getFormat("#")); // 遍历所有行,处理第4、5列(对应E、F列) for (int rowNum = new_sheet.getFirstRowNum(); rowNum <= new_sheet.getLastRowNum(); rowNum++) { XSSFRow row = new_sheet.getRow(rowNum); if (row == null) continue; int[] targetCols = {4, 5}; for (int colIndex : targetCols) { Cell cell = row.getCell(colIndex); if (cell == null) continue; // 仅处理当前为字符串类型的单元格 if (cell.getCellType() == CellType.STRING) { String cellContent = cell.getStringCellValue().trim(); try { // 把字符串内容转为数值写入,自动修改单元格类型为数值 double numValue = Double.parseDouble(cellContent); cell.setCellValue(numValue); // 绑定数值格式样式 cell.setCellStyle(numberStyle); } catch (NumberFormatException e) { // 内容不是合法数字的场景可自行补充处理逻辑 } } } } // 输出文件并关闭流 FileOutputStream fileOutputStream = new FileOutputStream(final_report_name); workBook.write(fileOutputStream); fileOutputStream.close(); workBook.close(); fis.close();
内容的提问来源于stack exchange,提问作者MM1122
相关产品推荐
相关产品推荐

