Excel檔案匯出後臺介面及工具類
阿新 • • 發佈:2018-12-16
有時專案中會有需求,是將內容匯出到excel表格中,參考網上的很多教程寫的都比較多,現在將主要程式碼寫成工具類,封裝成jar包。 一、接下來要展示的Excel匯出功能借助的是自己設定Excel模板,如下: 注意: 需要對第一列兩行設定備註: 1.設定你要匯出欄位的區域,到第幾行第幾列就寫上對應單元格號。(這裡是兩行兩列,所以到B2),如圖: 2.(1)設定items(存放你要匯出資訊的集合名,下面在寫匯出時產生的。) (2)設定var(要匯出資訊的實體類名稱) (3)設定lastCell(與上面一樣,欄位涉及單元格的範圍) 二、編寫Excel匯出業務:
//1.資訊放進Excel模板 @RequestMapping(value = "/export", method = RequestMethod.POST) public Map<String, Object> exports(@RequestBody QueryParam queryParam) throws IOException { Map<String, Object> varMap = new HashMap<>(); //直接資料庫查詢出來要匯出的全部資訊。(如果需要指定匯出的資料,前臺傳參,然後查詢匯出。這裡預設匯出所有資訊。) List<Person> personList = excelService.selectByFilter(queryParam); //personList:上面Excel備註中要用到的集合名稱 varMap.put("personList ", personList ); //templatePath:配置的Excel模板路徑(比如idea可以設定註解,配置在application.yml中),StringUtil.serial():Excel檔案加密後的名字,varMap:需要匯出到Excel的資訊 return ExcelUtil.exportFile(templatePath, "ExcelExport.xlsx", StringUtil.serial() + ".xlsx", "Excel匯出資訊.xlsx", varMap); } //2.下載Excel @RequestMapping(value="/download", method = RequestMethod.GET) public void download1(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName,@RequestParam(name = "originName", required = false) String originName) throws IOException { if (!StringUtils.isEmpty(originName)) { FileUtil.download(request, response, fileName, originName); } else { FileUtil.download(request, response, fileName); } }
說明: ExcelUtil、FileUtil、StringUtils:Excel匯入模板、Excel檔案下載、Excel名稱編碼這幾個類稍微有點多,已經封裝成jar包,具體另作展示(若有需要可以私聊)。