springBoot excel匯出 下載 超簡單
阿新 • • 發佈:2020-07-16
1.匯入maven依賴包
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.1</version> </dependency>
新建以下工具類
package com.mybatis.plus.excel; import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.support.ExcelTypeEnum; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.List;/** * @Author pt * @Description 工具類 * @Date 2018-06-06 * @Time 14:07 */ public class ExcelUtil { /** * 讀取 Excel(多個 sheet) * * @param excel 檔案 * @param rowModel 實體類對映,繼承 BaseRowModel 類 * @return Excel 資料 list */ public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) { ExcelListener excelListener= new ExcelListener(); ExcelReader reader = getReader(excel, excelListener); if (reader == null) { return null; } for (Sheet sheet : reader.getSheets()) { if (rowModel != null) { sheet.setClazz(rowModel.getClass()); } reader.read(sheet); }return excelListener.getDatas(); } /** * 讀取某個 sheet 的 Excel * * @param excel 檔案 * @param rowModel 實體類對映,繼承 BaseRowModel 類 * @param sheetNo sheet 的序號 從1開始 * @return Excel 資料 list */ public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) { return readExcel(excel, rowModel, sheetNo, 1); } /** * 讀取某個 sheet 的 Excel * * @param excel 檔案 * @param rowModel 實體類對映,繼承 BaseRowModel 類 * @param sheetNo sheet 的序號 從1開始 * @param headLineNum 表頭行數,預設為1 * @return Excel 資料 list */ public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo, int headLineNum) { ExcelListener excelListener = new ExcelListener(); ExcelReader reader = getReader(excel, excelListener); if (reader == null) { return null; } reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass())); return excelListener.getDatas(); } /** * 匯出 Excel :一個 sheet,帶表頭 * * @param response HttpServletResponse * @param list 資料 list,每個元素為一個 BaseRowModel * @param fileName 匯出的檔名 * @param sheetName 匯入檔案的 sheet 名 * @param object 對映實體類,Excel 模型 */ public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list, String fileName, String sheetName, BaseRowModel object) { ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX); Sheet sheet = new Sheet(1, 0, object.getClass()); sheet.setSheetName(sheetName); writer.write(list, sheet); writer.finish(); } /** * 匯出 Excel :多個 sheet,帶表頭 * * @param response HttpServletResponse * @param list 資料 list,每個元素為一個 BaseRowModel * @param fileName 匯出的檔名 * @param sheetName 匯入檔案的 sheet 名 * @param object 對映實體類,Excel 模型 */ public static ExcelWriterFactroy writeExcelWithSheets(HttpServletResponse response, List<? extends BaseRowModel> list, String fileName, String sheetName, BaseRowModel object) { ExcelWriterFactroy writer = new ExcelWriterFactroy(getOutputStream(fileName, response), ExcelTypeEnum.XLSX); Sheet sheet = new Sheet(1, 0, object.getClass()); sheet.setSheetName(sheetName); writer.write(list, sheet); return writer; } /** * 匯出檔案時為Writer生成OutputStream */ private static OutputStream getOutputStream(String fileName, HttpServletResponse response) { //建立本地檔案 String filePath = fileName + ".xlsx"; File dbfFile = new File(filePath); try { if (!dbfFile.exists() || dbfFile.isDirectory()) { dbfFile.createNewFile(); } fileName = new String(filePath.getBytes(), "ISO-8859-1"); response.addHeader("Content-Disposition", "filename=" + fileName); return response.getOutputStream(); } catch (IOException e) { throw new ExcelException("建立檔案失敗!"); } } /** * 返回 ExcelReader * * @param excel 需要解析的 Excel 檔案 * @param excelListener new ExcelListener() */ private static ExcelReader getReader(MultipartFile excel, ExcelListener excelListener) { String filename = excel.getOriginalFilename(); if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) { throw new ExcelException("檔案格式錯誤!"); } try { BufferedInputStream bufferedInputStream = new BufferedInputStream(excel.getInputStream()); return new ExcelReader(bufferedInputStream, null, excelListener, false); } catch (IOException e) { e.printStackTrace(); } return null; } }
package com.mybatis.plus.excel; /** * * * @Author pt * @Description Excel 解析 Exception * @Date 2018-06-06 * @Time 15:56 */ public class ExcelException extends RuntimeException { public ExcelException(String message) { super(message); } }
package com.mybatis.plus.excel; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import java.util.ArrayList; import java.util.List; /** * @Author pt * @Description 監聽類,可以自定義 * @Date 2018-06-05 * @Time 16:58 */ public class ExcelListener extends AnalysisEventListener { //自定義用於暫時儲存data。 //可以通過例項獲取該值 private List<Object> datas = new ArrayList<>(); /** * 通過 AnalysisContext 物件還可以獲取當前 sheet,當前行等資料 */ @Override public void invoke(Object object, AnalysisContext context) { //資料儲存到list,供批量處理,或後續自己業務邏輯處理。 datas.add(object); //根據業務自行 do something doSomething(); /* 如資料過大,可以進行定量分批處理 if(datas.size()<=100){ datas.add(object); }else { doSomething(); datas = new ArrayList<Object>(); } */ } /** * 根據業務自行實現該方法 */ private void doSomething() { } @Override public void doAfterAllAnalysed(AnalysisContext context) { /* datas.clear(); 解析結束銷燬不用的資源 */ } public List<Object> getDatas() { return datas; } public void setDatas(List<Object> datas) { this.datas = datas; } }
package com.mybatis.plus.excel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.support.ExcelTypeEnum; import java.io.IOException; import java.io.OutputStream; import java.util.List; /** * Created with IntelliJ IDEA * * @Author pt * @Description * @Date 2018-06-07 * @Time 16:47 */ public class ExcelWriterFactroy extends ExcelWriter { private OutputStream outputStream; private int sheetNo = 1; public ExcelWriterFactroy(OutputStream outputStream, ExcelTypeEnum typeEnum) { super(outputStream, typeEnum); this.outputStream = outputStream; } public ExcelWriterFactroy write(List<? extends BaseRowModel> list, String sheetName, BaseRowModel object) { this.sheetNo++; try { Sheet sheet = new Sheet(sheetNo, 0, object.getClass()); sheet.setSheetName(sheetName); this.write(list, sheet); } catch (Exception ex) { ex.printStackTrace(); try { outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } return this; } @Override public void finish() { super.finish(); try { outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } }
建立匯出表格對應實體
package com.mybatis.plus.dto; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.metadata.BaseRowModel; import lombok.Data; @Data public class ExcelTestDto extends BaseRowModel { @ExcelProperty(value = "字典描述") private String dictDesc; @ExcelProperty(value = "字典名稱") private String dictName; }
業務邏輯程式碼
@RequestMapping("export") public String export(HttpServletResponse response){ List<Dict> list = iDictService.list(); List<ExcelTestDto> excelDtos = new ArrayList<>(); for (Dict dict : list) { ExcelTestDto excelDto = new ExcelTestDto(); BeanUtil.copyProperties(dict,excelDto); excelDtos.add(excelDto); } String key = DateUtil.format(new Date(), "yyyy-MM-dd-HH-mm-ss"); // 配置檔案下載 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); ExcelUtil.writeExcel(response, excelDtos, key, "sheet1", new ExcelTestDto()); return "success"; }
最後在瀏覽器url輸入匯出介面地址 匯出效果