后台生成Excel時前端獲取下載
Controller控制器:
package com.example.test.controller; import com.example.test.common.HttpRequest; import com.example.test.utils.ExcelUtil; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; @Controller @RequestMapping(value = "/report") public class TestController { public HttpRequest hr = new HttpRequest(); /** * 導出Excel */ @RequestMapping(value = "/excel", produces = "application/json; charset=utf-8") @ResponseBody public void findExcel(HttpServletRequest request,HttpServletResponse response) { String startTime = request.getParameter("startTime"); startTime = startTime+" 00:00:00"; String endTime = request.getParameter("endTime"); endTime = endTime+" 00:00:00"; String param = "startTime="+startTime+"&endTime="+endTime; String baseURL = "http://localhost:8080"; String res = hr.sendPost(baseURL+"/getFinancingStat", param); System.out.println(res); List<JSONObject> list = JSONArray.fromObject(res); //excel標題 String[] title = {"業務員姓名","單量","業務員電話","業務員id"}; //excel文件名 String fileName = "業務員數據"+startTime+"至"+endTime+".xls"; //sheet名 String sheetName = "業務員數據"; String[][] content=new String[list.size()][title.length]; for (int i = 0; i < list.size(); i++) { content[i] = new String[title.length]; JSONObject obj=list.get(i); content[i][0] = obj.get("業務員姓名").toString(); content[i][1] = obj.get("單量").toString(); content[i][2] = obj.get("業務員電話").toString(); content[i][3] = obj.get("業務員id").toString(); } //創建HSSFWorkbook HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null); //響應到客戶端 try { this.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } //發送響應流方法 public void setResponseHeader(HttpServletResponse response, String fileName) { try { try { fileName = new String(fileName.getBytes(),"ISO8859-1"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.setContentType("application/octet-stream;charset=ISO8859-1"); response.setHeader("Content-Disposition", "attachment;filename="+ fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } } }
ExcelUtil生成Excel的樣式:
package com.example.test.utils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelUtil { /** * 導出Excel * @param sheetName sheet名稱 * @param title 標題 * @param values 內容 * @param wb HSSFWorkbook對象 * @return */ public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){ // 第一步,創建一個HSSFWorkbook,對應一個Excel文件 if(wb == null){ wb = new HSSFWorkbook(); } // 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet HSSFSheet sheet = wb.createSheet(sheetName); // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制 HSSFRow row = sheet.createRow(0); // 第四步,創建單元格,並設置值表頭 設置表頭居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式 //聲明列對象 HSSFCell cell = null; //創建標題 for(int i=0;i<title.length;i++){ cell = row.createCell(i); cell.setCellValue(title[i]); cell.setCellStyle(style); } //創建內容 for(int i=0;i<values.length;i++){ row = sheet.createRow(i + 1); for(int j=0;j<values[i].length;j++){ //將內容按順序賦給對應的列對象 row.createCell(j).setCellValue(values[i][j]); } } return wb; } }
前端頁面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="../js/jquery.js"></script> </head> <body> 開始時間:<input class="form-control" type="date" id="startTime" /><br/><br/> 結束時間:<input class="form-control" type="date" id="endTime" /><br/><br/> <button id="js-export" type="button" class="btn btn-primary">導出Excel</button> </body> <script> $('#js-export').click(function(){ var startTime = document.getElementById("startTime").value; var endTime = document.getElementById("endTime").value; window.location.href="/report/excel?startTime="+startTime+"&endTime="+endTime+""; }); </script> </html>
maven中的配置:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-examples</artifactId> <version>3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.11</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>