Java——使用EasyExcel导出动态列的Excel
短信预约 -IT技能 免费直播动态提醒
有些时候列表的列可能是动态的,需要根据动态表头导出Excel文件,这时候可以使用下面的方法解决:
public static void exportDynamicExcel(Set includeColumnFiledNames, String fileName, List list, Class clazz, HttpServletResponse response) { try { ServletOutputStream os = response.getOutputStream(); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); String encodeFileName = new String(fileName.getBytes(), "ISO8859-1"); response.setContentType("application/octet-stream;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName + ".xlsx"); ExcelWriterBuilder excelBuilder = EasyExcel.write(os, clazz); excelBuilder = includeColumnFiledName(includeColumnFiledNames, excelBuilder); excelBuilder.useDefaultStyle(false).sheet(fileName).doWrite(list); os.close(); } catch (IOException e) { e.printStackTrace(); } } private static ExcelWriterBuilder includeColumnFiledName(Set includeColumnFiledNames, ExcelWriterBuilder excelBuilder) { excelBuilder = excelBuilder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()); if (includeColumnFiledNames.size() > 0) { excelBuilder = excelBuilder.includeColumnFiledNames(includeColumnFiledNames); } excelBuilder = excelBuilder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()); return excelBuilder; }
静态列导出代码:
public static void exportExcel(String fileName, List list, Class clazz, HttpServletResponse response) { try { String fileNameFull = fileName + "(" + TimeUtils.getTime() + ")"; ServletOutputStream os = response.getOutputStream(); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); String encodeFileName = URLEncoder.encode(fileNameFull, "UTF-8"); response.setContentType("application/octet-stream;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName + ".xlsx"); EasyExcel.write(os, clazz).useDefaultStyle(false).sheet(fileName).doWrite(list); os.close(); } catch (IOException e) { e.printStackTrace(); } }
来源地址:https://blog.csdn.net/qq_26230421/article/details/130293297
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341