diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java index bd770eb2..05bf2bb4 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java @@ -20,7 +20,10 @@ import cn.hutool.core.util.IdUtil; import cn.hutool.poi.excel.BigExcelWriter; import cn.hutool.poi.excel.ExcelUtil; import me.zhengjie.exception.BadRequestException; +import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.util.IOUtils; +import org.apache.poi.xssf.streaming.SXSSFCell; +import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -214,6 +217,8 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { sheet.trackAllColumnsForAutoSizing(); //列宽自适应 writer.autoSizeColumnAll(); + //列宽自适应支持中文单元格 + sizeChineseColumn(sheet, writer); //response为HttpServletResponse对象 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 @@ -226,6 +231,33 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { IoUtil.close(out); } + /** + * 自适应宽度(中文支持) + */ + private static void sizeChineseColumn(SXSSFSheet sheet, BigExcelWriter writer) { + for (int columnNum = 0; columnNum < writer.getColumnCount(); columnNum++) { + int columnWidth = sheet.getColumnWidth(columnNum) / 256; + for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { + SXSSFRow currentRow; + if (sheet.getRow(rowNum) == null) { + currentRow = sheet.createRow(rowNum); + } else { + currentRow = sheet.getRow(rowNum); + } + if (currentRow.getCell(columnNum) != null) { + SXSSFCell currentCell = currentRow.getCell(columnNum); + if (currentCell.getCellTypeEnum() == CellType.STRING) { + int length = currentCell.getStringCellValue().getBytes().length; + if (columnWidth < length) { + columnWidth = length; + } + } + } + } + sheet.setColumnWidth(columnNum, columnWidth * 256); + } + } + public static String getFileType(String type) { String documents = "txt doc pdf ppt pps xlsx xls docx"; String music = "mp3 wav wma mpa ram ra aac aif m4a";