之前咱們經常使用get方式導出excel,比較簡單,可是對於請求參數有長度限制,要麼控制參數長度,要麼經過緩存的方式獲取參數,仍是有點麻煩。前端
今天講的是經過post方式導出excelios
先看前端代碼spring
responseType: "blob"這個很關鍵
async exportData() { axios({ method: "post", url: "/excel", data:this.query.data, responseType: "blob" }) .then(res => { // console.log(decodeURI(res.headers['filename'])); const link = document.createElement("a"); let blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); link.style.display = "none"; link.href = URL.createObjectURL(blob); link.setAttribute("download", decodeURI(res.headers['filename'])); document.body.appendChild(link); link.click(); document.body.removeChild(link); }) .catch(error => { this.$Notice.error({ title: "錯誤", desc: "系統數據錯誤" }); console.log(error); }); },
後臺springboot經過poi導出excelapache
Maven引入依賴axios
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>RELEASE</version> </dependency>
Controller層接受參數並處理數據,按理說不該該在這裏處理數據,爲了直觀先這樣了
@PostMapping(value = "excel") @ResponseBody public void excel() throws Exception { HttpServletRequest request = (HttpServletRequest) servletRequestAttributes.getRequest(); HttpServletResponse response = servletRequestAttributes.getResponse(); StringBuffer jb = new StringBuffer(); String line = null; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); params = JSON.parseObject(jb.toString(), PersonRequest.class); //.....省略表頭和數據處理 SimpleDateFormat fdate = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = title + fdate.format(new Date()) + ".xlsx"; ExcelUtil.exportExcel(response, fileName, data); }
ExcelUtil工具類
/** * 導出excel * @param response response * @param fileName 文件名 * @param data 數據 * @throws Exception */ public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception { // 告訴瀏覽器用什麼軟件能夠打開此文件 response.setHeader("content-Type", "application/vnd.ms-excel"); // 下載文件的默認名稱 response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8")); response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8")); response.setHeader("Access-Control-Expose-Headers", "FileName"); exportExcel(data, response.getOutputStream()); } public static void exportExcel(ExcelData data, OutputStream out) throws Exception { XSSFWorkbook wb = new XSSFWorkbook(); try { String sheetName = data.getName(); if (null == sheetName) { sheetName = "Sheet1"; } XSSFSheet sheet = wb.createSheet(sheetName); writeExcel(wb, sheet, data); wb.write(out); } catch(Exception e){ e.printStackTrace(); }finally{ //此處須要關閉 wb 變量 out.close(); } } private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) { int rowIndex = 0; rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles()); writeRowsToExcel(wb, sheet, data.getRows(), rowIndex); autoSizeColumns(sheet, data.getTitles().size() + 1); } private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) { int rowIndex = 0; int colIndex = 0; Font titleFont = wb.createFont(); titleFont.setFontName("simsun"); //titleFont.setBoldweight(Short.MAX_VALUE); // titleFont.setFontHeightInPoints((short) 14); titleFont.setColor(IndexedColors.BLACK.index); XSSFCellStyle titleStyle = wb.createCellStyle(); titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192))); titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); titleStyle.setFont(titleFont); setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0))); Row titleRow = sheet.createRow(rowIndex); // titleRow.setHeightInPoints(25); colIndex = 0; for (String field : titles) { Cell cell = titleRow.createCell(colIndex); cell.setCellValue(field); cell.setCellStyle(titleStyle); colIndex++; } rowIndex++; return rowIndex; } private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) { int colIndex = 0; Font dataFont = wb.createFont(); dataFont.setFontName("simsun"); // dataFont.setFontHeightInPoints((short) 14); dataFont.setColor(IndexedColors.BLACK.index); XSSFCellStyle dataStyle = wb.createCellStyle(); dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); dataStyle.setFont(dataFont); setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0))); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); for (List<Object> rowData : rows) { Row dataRow = sheet.createRow(rowIndex); // dataRow.setHeightInPoints(25); colIndex = 0; for (Object cellData : rowData) { Cell cell = dataRow.createCell(colIndex); if (cellData != null) { if(cellData instanceof Date) { cell.setCellValue(sdf.format(cellData)); } else { cell.setCellValue(cellData.toString()); } } else { cell.setCellValue(""); } cell.setCellStyle(dataStyle); colIndex++; } rowIndex++; } return rowIndex; } private static void autoSizeColumns(Sheet sheet, int columnNumber) { for (int i = 0; i < columnNumber; i++) { int orgWidth = sheet.getColumnWidth(i); sheet.autoSizeColumn(i, true); int newWidth = (int) (sheet.getColumnWidth(i) + 100); if (newWidth > orgWidth) { sheet.setColumnWidth(i, newWidth); } else { sheet.setColumnWidth(i, orgWidth); } } } private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) { style.setBorderTop(border); style.setBorderLeft(border); style.setBorderRight(border); style.setBorderBottom(border); style.setBorderColor(BorderSide.TOP, color); style.setBorderColor(BorderSide.LEFT, color); style.setBorderColor(BorderSide.RIGHT, color); style.setBorderColor(BorderSide.BOTTOM, color); }