1. 程式人生 > >Spring boot + poi web頁面匯出Excel

Spring boot + poi web頁面匯出Excel

首先,在pom.xml檔案引入poi

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.11</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11</version>
</dependency>

其次,建立excel檔案、新增sheet、設定表頭和新增表格內容

 public void outPutExcel (ArrayList<HashMap> dateMap, HttpServletResponse response) {
        String fileName = "xxx報表.xls";
        String[] headers = {"日期", "x1次數", "x2次數"};
        String title = "本報表由xxx生成";
        //建立一個Excel檔案
        HSSFWorkbook workbook = new HSSFWorkbook();
        //在Excel中新增一個sheet
        HSSFSheet sheet = workbook.createSheet(title);
        //在sheet中新增表頭d第0行
        HSSFRow row = sheet.createRow(0);
        //建立單元格,並設定表頭,表頭居中
        HSSFCellStyle style = workbook.createCellStyle();
        //建立一個居中格式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //建立標題
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //建立內容
        int rowNum = 1;
        for (HashMap date : dateMap) {
            HSSFRow hssfRow = sheet.createRow(rowNum);
            hssfRow.createCell(0).setCellValue(String.valueOf(date.get("date")));
            hssfRow.createCell(1).setCellValue(String.valueOf(date.get("imp")));
            hssfRow.createCell(2).setCellValue(String.valueOf(date.get("u_imp")));
            rowNum++;
        }
        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");
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

Controller層

@RequestMapping(value = "/excel", method = RequestMethod.GET)
@ResponseBody
public void downloadReport(HttpServletRequest request, HttpServletResponse response) {
    ArrayList<HashMap> reportMap = xxxService.xxxxxx();
    dspReportsService.outPutExcel(reportMap, response);
}