前言
多多点赞,会变好看!
多多留言,会变有钱!
有些时候列表的列可能是动态的,需要根据动态表头导出Excel文件,这时候可以使用下面的方法解决:文章来源:https://www.toymoban.com/news/detail-608826.html
/**
* 使用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;
}
扩展
静态列导出代码:文章来源地址https://www.toymoban.com/news/detail-608826.html
/**
* 使用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();
}
}
到了这里,关于Java——使用EasyExcel导出动态列的Excel的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!