有些时候列表的列可能是动态的,需要根据动态表头导出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