700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Hutool工具类ExcelWriter导出excel列宽自适应问题解决

Hutool工具类ExcelWriter导出excel列宽自适应问题解决

时间:2023-04-04 00:42:22

相关推荐

Hutool工具类ExcelWriter导出excel列宽自适应问题解决

前言:

因为项目中需要使用到ExcelWriter导出excel的列宽自适应,下面为解决该问题的经过,希望可以对遇到同样问题的开发者有所帮助。

一、通过查询Hutool官方的api文档发现autoSizeColumn()方法

官方api链接

但是,在代码中使用该方法后发现并没有起作用。

二、通过搜索发现其他开发者使用Sheet强制转换为SXSSFSheet,后再调用改方法可以成功设置自适应。

SXSSFSheet sheet = (SXSSFSheet) writer.getSheet();sheet.trackAllColumnsForAutoSizing();writer.autoSizeColumnAll();

再次尝试使用后报错:

java.lang.ClassCastException: org.apache.poi.hssf.usermodel.HSSFSheet cannot be cast to org.apache.poi.xssf.streaming.SXSSFSheet

三、自定义方法

/*** 自适应宽度(中文支持)* @param sheet* @param size 因为for循环从0开始,size值为 列数-1*/public static void setSizeColumn(Sheet sheet, int size) {for (int columnNum = 0; columnNum <= size; columnNum++) {int columnWidth = sheet.getColumnWidth(columnNum) / 256;for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {Row currentRow;//当前行未被使用过if (sheet.getRow(rowNum) == null) {currentRow = sheet.createRow(rowNum);} else {currentRow = sheet.getRow(rowNum);}if (currentRow.getCell(columnNum) != null) {Cell currentCell = currentRow.getCell(columnNum);if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {int length = currentCell.getStringCellValue().getBytes().length;if (columnWidth < length) {columnWidth = length;}}}}sheet.setColumnWidth(columnNum, columnWidth * 256);}}

问题解决,可以实现列宽自适应。

效果展示:

大神的解决办法:

根据大神的评论,我调用的位置可能不对,要在写出内容后调用才会生效。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。