Hutool工具使用Excel部分常见问题总结

时间:2025-03-10 14:15:32
  1. 当写完行数据之后想在行后面继续增加数据有时会报错该行已经写入硬盘无法再访问,此时设置无限制访问Excel表格即可
SXSSFSheet sheet = (SXSSFSheet) writer.getSheet();
sheet.setRandomAccessWindowSize(-1);//无限制访问sheet
  • 1
  • 2
  1. Excel的宽度自适应代码(大量数据时以下代码会耗时较久,建议慎用)
sheet.trackAllColumnsForAutoSizing();
writer.autoSizeColumnAll();//自适应宽度
  • 1
  • 2
  1. 自定义单元格格式
CellStyle defaultCellStyle = StyleUtil.createDefaultCellStyle(writer.getWorkbook());
defaultCellStyle.setAlignment(HorizontalAlignment.RIGHT);//对齐方式
DataFormat format = writer.getWorkbook().createDataFormat();
defaultCellStyle.setDataFormat((format.getFormat("0.00")));//格式化两位小数(数据为BigDecimal类型)
dateCellStyle.setDataFormat((format.getFormat("yyyy-mm-dd hh:mm:ss")));//自定义时间格式(数据为Date类型)

writer.setStyle(dateCellStyle, i, j);//以坐标形式指定写入某个单元格的格式
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 解决生成的Excel数字部分无法进行数学运算(求和之类的)的问题
		CellStyle fourCellStyle = StyleUtil.createDefaultCellStyle(writer.getWorkbook());
        fourCellStyle.setAlignment(HorizontalAlignment.RIGHT);
        fourCellStyle.setDataFormat((format.getFormat("0.0000")));//格式化4位小数
        for (int j = 1; j <= dataCount; j++) {
            int i = 5;
            //转换单位格值为数字类型
            Cell cell = writer.getCell(i,j);
            if(cell != null && cell.getCellType() == CellType.STRING){
                if(StringUtils.isNotBlank(cell.getStringCellValue())){
                    writer.writeCellValue(i,j,new BigDecimal(cell.getStringCellValue()));
                }
            }
            writer.setStyle(fourCellStyle, i, j);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14