当前位置:   article > 正文

Java——使用EasyExcel导出动态列的Excel_easyexcel 动态列

easyexcel 动态列

前言

多多点赞,会变好看!

多多留言,会变有钱!

有些时候列表的列可能是动态的,需要根据动态表头导出Excel文件,这时候可以使用下面的方法解决:

  1. /**
  2. * 使用EasyExcel导出动态Excel
  3. * @param includeColumnFiledNames
  4. * @param fileName
  5. * @param list
  6. * @param clazz
  7. * @param response
  8. */
  9. public static void exportDynamicExcel(Set<String> includeColumnFiledNames, String fileName, List list, Class clazz, HttpServletResponse response) {
  10. try {
  11. ServletOutputStream os = response.getOutputStream();
  12. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  13. response.setCharacterEncoding("utf-8");
  14. String encodeFileName = new String(fileName.getBytes(), "ISO8859-1");
  15. response.setContentType("application/octet-stream;charset=UTF-8");
  16. response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName + ".xlsx");
  17. ExcelWriterBuilder excelBuilder = EasyExcel.write(os, clazz);
  18. excelBuilder = includeColumnFiledName(includeColumnFiledNames, excelBuilder);
  19. excelBuilder.useDefaultStyle(false).sheet(fileName).doWrite(list);
  20. os.close();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. private static ExcelWriterBuilder includeColumnFiledName(Set<String> includeColumnFiledNames, ExcelWriterBuilder excelBuilder) {
  26. excelBuilder = excelBuilder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
  27. if (includeColumnFiledNames.size() > 0) {
  28. excelBuilder = excelBuilder.includeColumnFiledNames(includeColumnFiledNames);
  29. }
  30. excelBuilder = excelBuilder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
  31. return excelBuilder;
  32. }

扩展

静态列导出代码:

  1. /**
  2. * 使用EasyExcel导出Excel
  3. */
  4. public static void exportExcel(String fileName, List list, Class clazz, HttpServletResponse response) {
  5. try {
  6. String fileNameFull = fileName + "(" + TimeUtils.getTime() + ")";
  7. ServletOutputStream os = response.getOutputStream();
  8. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  9. response.setCharacterEncoding("utf-8");
  10. String encodeFileName = URLEncoder.encode(fileNameFull, "UTF-8");
  11. response.setContentType("application/octet-stream;charset=UTF-8");
  12. response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName + ".xlsx");
  13. EasyExcel.write(os, clazz).useDefaultStyle(false).sheet(fileName).doWrite(list);
  14. os.close();
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/584415
推荐阅读
相关标签
  

闽ICP备14008679号