From 7bb4ade348b1fdc96de00ebf4a43b0108b506013 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9A=86=E9=9D=9E?= <53246310+jie-fei30@users.noreply.github.com> Date: Sun, 8 Nov 2020 10:20:14 +0800 Subject: [PATCH] =?UTF-8?q?[=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96](v2.6)?= =?UTF-8?q?=EF=BC=9A=E5=AF=BC=E5=87=BAexcel=E6=97=B6=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=B8=AD=E6=96=87=E5=AD=97=E7=AC=A6=E5=8D=95=E5=85=83=E6=A0=BC?= =?UTF-8?q?=E5=88=97=E5=AE=BD=E8=87=AA=E9=80=82=E5=BA=94=20(#516)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/me/zhengjie/utils/FileUtil.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) 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";