本文主要是介绍hutool工具包导出excel文件filename乱码与中文列宽自适应问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
hutool工具包导出excel文件filename乱码与中文列宽自适应问题
*话不多说,直接代码~~~~*
修改之前:
/*** 导出excel*/public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";File file = new File(tempPath);BigExcelWriter writer = ExcelUtil.getBigWriter(file);// 一次性写出内容,使用默认样式,强制输出标题writer.write(list, true);SXSSFSheet sheet = (SXSSFSheet)writer.getSheet();//上面需要强转SXSSFSheet 不然没有trackAllColumnsForAutoSizing方法sheet.trackAllColumnsForAutoSizing();//列宽自适应writer.autoSizeColumnAll();//response为HttpServletResponse对象response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");ServletOutputStream out = response.getOutputStream();// 终止后删除临时文件file.deleteOnExit();writer.flush(out, true);//此处记得关闭输出Servlet流IoUtil.close(out);}
修改之后:
/*** 导出excel* 增加自定义excel名称功能*/public static void downloadExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";File file = new File(tempPath);BigExcelWriter writer = ExcelUtil.getBigWriter(file);// 一次性写出内容,使用默认样式,强制输出标题writer.write(list, true);SXSSFSheet sheet = (SXSSFSheet) writer.getSheet();//上面需要强转SXSSFSheet 不然没有trackAllColumnsForAutoSizing方法sheet.trackAllColumnsForAutoSizing();//列宽自适应writer.autoSizeColumnAll();//默认取第一行数据,解决中文自适应宽度不足问题if (sheet != null && sheet.getRow(1) != null) {int physicalNumberOfCells = sheet.getRow(1).getPhysicalNumberOfCells();for (int i = 0; i < physicalNumberOfCells; i++) {// 调整每一列宽度sheet.autoSizeColumn((short) i);// 解决自动设置列宽中文失效的问题sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);}}//response为HttpServletResponse对象response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF8") + ".xlsx");ServletOutputStream out = response.getOutputStream();// 终止后删除临时文件file.deleteOnExit();writer.flush(out, true);//此处记得关闭输出Servlet流IoUtil.close(out);}
这篇关于hutool工具包导出excel文件filename乱码与中文列宽自适应问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!