|
@@ -20,6 +20,9 @@ import java.util.List;
|
|
|
* @author Rayson
|
|
|
*/
|
|
|
public class ExcelUtils {
|
|
|
+ private final static String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
|
+ private final static String XLS = "application/vnd.ms-excel;charset=UTF-8";
|
|
|
+
|
|
|
|
|
|
/**
|
|
|
* 将列表以 Excel 响应给前端
|
|
@@ -34,6 +37,9 @@ public class ExcelUtils {
|
|
|
*/
|
|
|
public static <T> void write(HttpServletResponse response, String filename, String sheetName,
|
|
|
Class<T> head, List<T> data) throws IOException {
|
|
|
+ // 设置 header 和 contentType。写在最后的原因是,避免报错时,响应 contentType 已经被修改了
|
|
|
+ response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
|
|
|
+ response.setContentType(filename.contains(".xlsx") ? XLSX : XLS);
|
|
|
// 输出 Excel
|
|
|
EasyExcel.write(response.getOutputStream(), head)
|
|
|
.autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
|
|
@@ -41,9 +47,6 @@ public class ExcelUtils {
|
|
|
.registerWriteHandler(new SelectSheetWriteHandler(head)) // 基于固定 sheet 实现下拉框
|
|
|
.registerConverter(new LongStringConverter()) // 避免 Long 类型丢失精度
|
|
|
.sheet(sheetName).doWrite(data);
|
|
|
- // 设置 header 和 contentType。写在最后的原因是,避免报错时,响应 contentType 已经被修改了
|
|
|
- response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
|
|
|
- response.setContentType("application/vnd.ms-excel;charset=UTF-8");
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -59,7 +62,7 @@ public class ExcelUtils {
|
|
|
throws IOException {
|
|
|
// 设置 header 和 contentType。写在最后的原因是,避免报错时,响应 contentType 已经被修改了
|
|
|
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
|
|
|
- response.setContentType("application/vnd.ms-excel;charset=UTF-8");
|
|
|
+ response.setContentType(filename.contains(".xlsx") ? XLSX : XLS);
|
|
|
try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).autoCloseStream(false).build()) {
|
|
|
for (ExcelWriteDTO writeDTO : writeDTOList) {
|
|
|
WriteSheet writeSheet = null;
|