springBoot整合easyPOI輕鬆實現Excel檔案匯出
阿新 • • 發佈:2019-01-04
首先吐槽以下!網上的很多經驗要不就是缺資訊,要不就是缺配置,反正總的來說,找了很久才實現的一個功能,今天分享給大家,讓大家輕鬆完成匯出Excel任務
非常感謝這位朋友的詳細解答,最終實現了這個功能,朋友們可以去看看
(1)用到的框架是easyPOI不知道的小夥伴可以去百度瞭解一下
maven匯入依賴
<!-- easyPOI --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>3.0.3</version> </dependency>
(2)相應的controller層配置(這裡的業務主要交給service層進行操作)
@RequestMapping(value = "exportStuInfoExcel")
@ResponseBody
public void exportStuInfoExcel(HttpServletResponse response){
stuService.downExcel(response);
}
(3)相應的service層配置
public void downExcel(HttpServletResponse response){ List<Student> list = getAllStu(); System.out.println(list.toString()); //指定列表標題和工作表名稱 ExportParams params = new ExportParams("學生資訊表","學生"); Workbook workbook = ExcelExportUtil.exportExcel(params,Student.class,list); response.setHeader("content-Type","application/vnd.ms-excel"); response.setHeader("Content-Disposition","attachment;filename="+System.currentTimeMillis()+".xls"); response.setCharacterEncoding("UTF-8"); try { workbook.write(response.getOutputStream()); workbook.close(); } catch (IOException e) { e.printStackTrace(); } }
上面的list是我自己建立的方法,也在service層內,可以直接呼叫
public List<Student> getAllStu(){
return stuRepository.findAll();
}
另外----上面的這個方法中的findAll()用的是JPA有興趣的朋友可以去學習一下
(4)對應的jsp頁面
<div><a href="/student/exportStuInfoExcel">匯出Excel表格</a></div>