使用poi實現Excel下載
阿新 • • 發佈:2019-02-09
參考了一下文章:
https://www.cnblogs.com/lcngu/p/7056875.html
前端:
HTML +angularJS :
HTML:
<a href="#" ng-click="export()">Export</a>JS:
$scope.export = function () { $http({ method: "POST", url: "/b", responseType: "arraybuffer" }).then( function successCallback(response) { var後端:(springboot)blob = new Blob([response.data], {type: "application/vnd.ms-excel"}); var fileName = "workloadReports"; var a = document.createElement("a"); document.body.appendChild(a); a.download = fileName; a.href = URL.createObjectURL(blob); a.click(); }, function errorCallback(response) { //debugger; } ); }
@RequestMapping(value = "/b", method = RequestMethod.POST) public void exportDataAsXls(HttpServletResponse response) { logger.info("exportDataAsXls start"); // 第一步,建立一個webbook,對應一個Excel檔案HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet HSSFSheet sheet = wb.createSheet("sheet1"); // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short HSSFRow row = sheet.createRow((int) 0); // 第四步,建立單元格,並設定值表頭 設定標頭樣式 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.CORAL.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); HSSFCell cell; String header = "a,b,c"; String[] headers=header.split(","); for (int i = 0; i < headers.length; i++) { cell = row.createCell(i); cell.setCellValue(headers[i]); cell.setCellStyle(cellStyle); } // 第五步,寫入實體資料data,實際應用中這些資料從資料庫得到, if(data== null){ return; } for(int j=0;j< data.size();j++){ Data data = data.get(j); row = sheet.createRow(j + 1); row.createCell(0).setCellValue(data.a()); row.createCell(1).setCellValue(data.b()); row.createCell(2).setCellValue(data.c()); } // 第六步,將檔案通過response輸出 try { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=createList.xls");//預設Excel名稱 response.flushBuffer(); wb.write(response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } logger.info("exportDataAsXls end"); }