Skip to content

Commit 7bb4ade

Browse files
authored
[代码优化](v2.6):导出excel时支持中文字符单元格列宽自适应 (elunez#516)
1 parent c7e95d9 commit 7bb4ade

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020
import cn.hutool.poi.excel.BigExcelWriter;
2121
import cn.hutool.poi.excel.ExcelUtil;
2222
import me.zhengjie.exception.BadRequestException;
23+
import org.apache.poi.ss.usermodel.CellType;
2324
import org.apache.poi.util.IOUtils;
25+
import org.apache.poi.xssf.streaming.SXSSFCell;
26+
import org.apache.poi.xssf.streaming.SXSSFRow;
2427
import org.apache.poi.xssf.streaming.SXSSFSheet;
2528
import org.slf4j.Logger;
2629
import org.slf4j.LoggerFactory;
@@ -214,6 +217,8 @@ public static void downloadExcel(List<Map<String, Object>> list, HttpServletResp
214217
sheet.trackAllColumnsForAutoSizing();
215218
//列宽自适应
216219
writer.autoSizeColumnAll();
220+
//列宽自适应支持中文单元格
221+
sizeChineseColumn(sheet, writer);
217222
//response为HttpServletResponse对象
218223
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
219224
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
@@ -226,6 +231,33 @@ public static void downloadExcel(List<Map<String, Object>> list, HttpServletResp
226231
IoUtil.close(out);
227232
}
228233

234+
/**
235+
* 自适应宽度(中文支持)
236+
*/
237+
private static void sizeChineseColumn(SXSSFSheet sheet, BigExcelWriter writer) {
238+
for (int columnNum = 0; columnNum < writer.getColumnCount(); columnNum++) {
239+
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
240+
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
241+
SXSSFRow currentRow;
242+
if (sheet.getRow(rowNum) == null) {
243+
currentRow = sheet.createRow(rowNum);
244+
} else {
245+
currentRow = sheet.getRow(rowNum);
246+
}
247+
if (currentRow.getCell(columnNum) != null) {
248+
SXSSFCell currentCell = currentRow.getCell(columnNum);
249+
if (currentCell.getCellTypeEnum() == CellType.STRING) {
250+
int length = currentCell.getStringCellValue().getBytes().length;
251+
if (columnWidth < length) {
252+
columnWidth = length;
253+
}
254+
}
255+
}
256+
}
257+
sheet.setColumnWidth(columnNum, columnWidth * 256);
258+
}
259+
}
260+
229261
public static String getFileType(String type) {
230262
String documents = "txt doc pdf ppt pps xlsx xls docx";
231263
String music = "mp3 wav wma mpa ram ra aac aif m4a";

0 commit comments

Comments
 (0)