能夠用前端js導,也能夠使用後端的POI導出html
前端導出前端
base64(s) { return window.btoa(unescape(encodeURIComponent(s))) }, exportExcel() { // 前端導出excel console.log(this.showList) let str = '<tr><td>代理名稱</td><td>allianceid</td><td>attachmentFileId</td>' for (let i = 0; i < this.showList.length; i++) { str += '<tr>' for (let item in this.showList[i]) { // 增長\t爲了避免讓表格顯示科學計數法或者其餘格式 str += `<td>${this.showList[i][item] + '\t'}</td>` } str += '</tr>' } let worksheet = 'Sheet1' let uri = 'data:application/vnd.ms-excel;base64,' // 下載的表格模板數據 let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet> <x:Name>${worksheet}</x:Name> <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet> </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </head><body><table>${str}</table></body></html>` // 下載模板 window.location.href = uri + this.base64(template) },//showList是table數據
後端POI導出excel後端
public static ResponseEntity<byte[]> export(List<Position> pos) throws IOException { //建立一個 excel 文檔 HSSFWorkbook workbook = new HSSFWorkbook(); //建立 excel 屬性配置 workbook.createInformationProperties(); //獲取而且配置文檔屬性 DocumentSummaryInformation information = workbook.getDocumentSummaryInformation(); information.setCategory("職位表"); information.setManager("管理員"); information.setCompany("liy"); //建立表單 HSSFSheet sheet = workbook.createSheet(); HSSFRow row = sheet.createRow(0); HSSFCell c0 = row.createCell(0); HSSFCell c1 = row.createCell(1); HSSFCell c2 = row.createCell(2); HSSFCell c3 = row.createCell(3); c0.setCellValue("編號"); c1.setCellValue("職位名稱"); c2.setCellValue("建立日期"); c3.setCellValue("是否可用"); HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); for (int i = 0; i < pos.size(); i++) { Position position = pos.get(i); HSSFRow r = sheet.createRow(i + 1); HSSFCell cl0 = r.createCell(0); HSSFCell cl1 = r.createCell(1); HSSFCell cl2 = r.createCell(2); HSSFCell cl3 = r.createCell(3); cl0.setCellValue(position.getId()); cl1.setCellValue(position.getName()); cl2.setCellValue(position.getCreatedate()); cl2.setCellStyle(cellStyle); cl3.setCellValue(position.getEnabled()?"是":"否"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); workbook.write(baos); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment",new String("職位表.xls".getBytes("UTF-8"),"iso-8859-1")); return new ResponseEntity<byte[]>(baos.toByteArray(),headers, HttpStatus.CREATED); }