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);
}

猜你喜欢

转载自blog.csdn.net/jiangxiaoyi_07/article/details/85245586