Spring Boot整合EasyExcel(完整版包含上傳解析excel和下載模板)
1. 加入依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.7</version> </dependency>
2. 對讀取excel內容(批量添加)
@PostMapping("plUpdate") public R plUpdate(@RequestParam("filename") MultipartFile file) throws IOException { //String Originalfilename = file.getOriginalFilename(); // String fileName = file.getName(); // System.out.println("orname="+Originalfilename+";"+"filename"+file.getName()); // 獲取文件全名 String fileName = file.getOriginalFilename(); //設置文件路徑 String templatePath = "G:/excel/"; File dest0 = new File(templatePath); File dest = new File(dest0, fileName); //文件上傳-覆蓋 try { // 檢測是否存在目錄 if (!dest0.getParentFile().exists()) { dest0.getParentFile().mkdirs(); //檢測文件是否存在 } if (!dest.exists()) { dest.mkdirs(); } file.transferTo(dest); } catch (Exception e) { return R.error(); } String finameUrl = templatePath+fileName; ExcelReader excelReader = null; try { //TeacherExcel.class對應的是和模板一樣的實體類, //eduTeacherService對應持久層的接口 excelReader = EasyExcel.read(finameUrl, TeacherExcel.class, new DemoDataListener(eduTeacherService)).build(); ReadSheet readSheet = EasyExcel.readSheet(0).build(); excelReader.read(readSheet); } finally { if (excelReader != null) { // 這裡千萬別忘記關閉,讀的時候會創建臨時文件,到時磁盤會崩的 excelReader.finish(); } } return R.ok(); }
創建一個監聽類:
package com.atguigu.excel; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.atguigu.eduservice.entity.EduTeacher; import com.atguigu.eduservice.entity.vo.TeacherExcel; import com.atguigu.eduservice.service.EduTeacherService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; // 有個很重要的點 DemoDataListener 不能被spring管理,要每次讀取excel都要new,然後裡面用到spring可以構造方法傳進去 public class DemoDataListener extends AnalysisEventListener<TeacherExcel> { private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class); //這裡寫持久層的類 private EduTeacherService eduTeacherService; /** * 如果使用瞭spring,請使用這個構造方法。每次創建Listener的時候需要把spring管理的類傳進來 * * @param eduTeacherService */ public DemoDataListener( EduTeacherService eduTeacherService) { //進行持久層的類 this.eduTeacherService = eduTeacherService; } /** * 每隔5條存儲數據庫,實際使用中可以3000條,然後清理list ,方便內存回收 */ private static final int BATCH_COUNT = 5; List<TeacherExcel> list = new ArrayList<TeacherExcel>(); /** * 假設這個是一個DAO,當然有業務邏輯這個也可以是一個service。當然如果不用存儲這個對象沒用。 */ //private DemoDAO demoDAO; public DemoDataListener() { // 這裡是demo,所以隨便new一個。實際使用如果到瞭spring,請使用下面的有參構造函數 //demoDAO = new DemoDAO(); } /** * 如果使用瞭spring,請使用這個構造方法。每次創建Listener的時候需要把spring管理的類傳進來 * * @param demoDAO */ /* public DemoDataListener(DemoDAO demoDAO) { this.demoDAO = demoDAO; }*/ /** * 這個每一條數據解析都會來調用 * * @param data * one row value. Is is same as {@link AnalysisContext#readRowHolder()} * @param context */ @Override public void invoke(TeacherExcel data, AnalysisContext context) { LOGGER.info("解析到一條數據:{}",data.toString()); list.add(data); // 達到BATCH_COUNT瞭,需要去存儲一次數據庫,防止數據幾萬條數據在內存,容易OOM } /** * 所有數據解析完成瞭 都會來調用 * * @param context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // 這裡也要保存數據,確保最後遺留的數據也存儲到數據庫 saveData(); LOGGER.info("所有數據解析完成!"); } /** * 加上存儲數據庫 */ private void saveData() { LOGGER.info("{}條數據,開始存儲數據庫!", list.size()); //因為我excel模板的實體和插入數據庫實體的類不一樣,所以需要進行轉化 for (int i =0;i<list.size();i++ ){ EduTeacher teacher = new EduTeacher(); teacher.setLevel(list.get(i).getLevel()); teacher.setCareer(list.get(i).getCareer()); teacher.setName(list.get(i).getName()); teacher.setSort(list.get(i).getSort()); teacher.setIntro(list.get(i).getIntro()); boolean save = eduTeacherService.save(teacher); if (save){ System.out.println("第"+i+"添加成功"); } } } }
例如我的excel模板是:
實體類:
字段上ExcelProperty的註解可以使用index聲明字段在模板中的順序,使用value聲明模板各個字段的名稱。
例如:
@ExcelProperty(value = “講師簡介”,index = 1) private String intro;
模板的實體類要和excel字段一樣對應,不然會出錯
效果:
3. 模板下載:
創建一個工具類:
package com.atguigu.eduservice.config; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.metadata.style.WriteCellStyle; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; import org.apache.poi.ss.usermodel.HorizontalAlignment; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; /** * @author linjiazeng * @version 1.0 * @date 2020/12/28 22:29 **/ public class ExcelUtil { /** * 導出 * @param response * @param data * @param fileName * @param sheetName * @param clazz * @throws Exception */ public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class clazz) throws Exception { //表頭樣式 WriteCellStyle headWriteCellStyle = new WriteCellStyle(); //設置表頭居中對齊 headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); //內容樣式 WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); //設置內容靠左對齊 contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT); HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); EasyExcel.write(getOutputStream(fileName, response), clazz).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy).doWrite(data); } private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception { fileName = URLEncoder.encode(fileName, "UTF-8"); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); response.addHeader("Access-Control-Expose-Headers", "Content-disposition"); return response.getOutputStream(); } }
調用工具類下載模板
/*下載模板*/ @GetMapping("/download/template") public void downloadTemplate(HttpServletResponse response){ String fileName = "導入講師模板"; String sheetName="導入講師模板"; List<TeacherExcel> teacherExcelList = new ArrayList<>(); TeacherExcel teacherExcel = new TeacherExcel(); teacherExcel.setName("ljz"); teacherExcel.setIntro("清華畢業,高材生"); teacherExcel.setCareer("資深講師"); teacherExcel.setSort(1); teacherExcel.setLevel(1); teacherExcelList.add(teacherExcel); try { //TeacherExcel.class對應你的模板類 //teacherExcelList模板的例子 //也可以使用這種方式導出你查詢出數據excel文件 ExcelUtil.writeExcel(response,teacherExcelList,fileName,sheetName,TeacherExcel.class); } catch (Exception e) { System.out.println(e.getCause()); } }
效果:
有問題可以互相交流,也可以去EasyExcel官網學習
到此這篇關於Spring Boot整合EasyExcel(完整版包含上傳解析excel和下載模板)的文章就介紹到這瞭,更多相關SpringBoot整合EasyExcel內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Java中利用Alibaba開源技術EasyExcel來操作Excel表的示例代碼
- java操作excel表格詳解
- 使用SpringBoot+EasyExcel+Vue實現excel表格的導入和導出詳解
- Java+EasyExcel實現文件的導入導出
- Java easyExcel的復雜表頭多級表頭導入