参考了一下文章:
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 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; } ); }后端:(springboot)
@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"); }