2020import cn .hutool .poi .excel .BigExcelWriter ;
2121import cn .hutool .poi .excel .ExcelUtil ;
2222import me .zhengjie .exception .BadRequestException ;
23+ import org .apache .poi .ss .usermodel .CellType ;
2324import org .apache .poi .util .IOUtils ;
25+ import org .apache .poi .xssf .streaming .SXSSFCell ;
26+ import org .apache .poi .xssf .streaming .SXSSFRow ;
2427import org .apache .poi .xssf .streaming .SXSSFSheet ;
2528import org .slf4j .Logger ;
2629import 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