有些时候列表的列可能是动态的,需要根据动态表头导出Excel文件,这时候可以使用下面的方法解决:
/** * 使用EasyExcel导出动态Excel * @param includeColumnFiledNames * @param fileName * @param list * @param clazz * @param response */ public static void exportDynamicExcel(Set<String> 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<String> includeColumnFiledNames, ExcelWriterBuilder excelBuilder) { excelBuilder = excelBuilder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()); if (includeColumnFiledNames.size() > 0) { excelBuilder = excelBuilder.includeColumnFiledNames(includeColumnFiledNames); } excelBuilder = excelBuilder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()); return excelBuilder; }
扩展
静态列导出代码:
/** * 使用EasyExcel导出Excel */ 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(); } }