From b71a687d9c592709421ae22760113ec3812ab80f Mon Sep 17 00:00:00 2001 From: wuy <1311695042@qq.com> Date: Wed, 1 Jul 2020 14:13:58 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E5=A2=9E=E5=8A=A0excel=E5=AF=BC?= =?UTF-8?q?=E5=85=A5=E5=B8=AE=E5=8A=A9=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diboot/file/util/ExcelHelper.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/diboot-file-starter/src/main/java/com/diboot/file/util/ExcelHelper.java b/diboot-file-starter/src/main/java/com/diboot/file/util/ExcelHelper.java index 5d97e87..eb66754 100644 --- a/diboot-file-starter/src/main/java/com/diboot/file/util/ExcelHelper.java +++ b/diboot-file-starter/src/main/java/com/diboot/file/util/ExcelHelper.java @@ -26,7 +26,10 @@ import com.diboot.file.excel.listener.DynamicHeadExcelListener; import com.diboot.file.excel.listener.FixedHeadExcelListener; import lombok.extern.slf4j.Slf4j; +import javax.servlet.http.HttpServletResponse; import java.io.File; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; @@ -114,6 +117,39 @@ public class ExcelHelper { } } + /** + * web 导出excel + * + * @param response + * @param clazz 导出的类 + * @param data 导出的数据 + * @param + * @throws Exception + */ + public static void exportExcel(HttpServletResponse response, String fileName,Class clazz, List data) throws Exception{ + try { + response.setContentType("application/x-msdownload"); + response.setCharacterEncoding("utf-8"); + fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); + response.setHeader("Content-disposition", "attachment; filename=" + fileName); + response.setHeader("filename", fileName); + response.setHeader("err-code", String.valueOf(Status.OK.code())); + response.setHeader("err-msg", URLEncoder.encode("操作成功", StandardCharsets.UTF_8.name())); + // 这里需要设置不关闭流 + EasyExcel.write(response.getOutputStream(), clazz) + .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) + .autoCloseStream(Boolean.FALSE) + .sheet("sheet1") + .doWrite(data); + } catch (Exception e) { + log.error("下载文件失败:", e); + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.setHeader("err-code", String.valueOf(Status.FAIL_OPERATION.code())); + response.setHeader("err-msg", URLEncoder.encode("下载文件失败", StandardCharsets.UTF_8.name())); + } + } + private static File getExcelFile(String filePath){ File file = new File(filePath); if(!file.exists()){