Skip to content

导出excel

GeXiangDong edited this page Jan 2, 2019 · 4 revisions

pom文件增加依赖

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

做一个excel模板文件放到src/main/resources目录下

最好再建个子目录,使用模板调格式会方便很多(宽度、字体、数字格式等等)

Controller里增加方法

    @GetMapping(value="/exportexcel", produces="application/excel")
    public ResponseEntity<byte[]> exportExcel() throws Exception{
        if(log.isTraceEnabled()) {
            log.trace("exportExcel");
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentDispositionFormData("attachment","testExcel.xlsx");
        responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        InputStream templateIs = this.getClass().getResourceAsStream("/excel-templates/excel-template.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(templateIs);
        XSSFSheet sheet = workbook.getSheetAt(0);

        XSSFRow rowHead = sheet.createRow(0);

        //这些写在模板里更好
        String[] headers = new String[]{"日期", "姓名", "年龄"};
        for(int i=0; i<headers.length; i++){
            Cell cellHeader = rowHead.createCell(i);
            cellHeader.setCellValue(headers[i]);
        }

        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> m1 = new HashMap<>();
        m1.put("date", new Date());
        m1.put("name", "张三");
        m1.put("num", 3);
        data.add(m1);
        Map<String, Object> m2 = new HashMap<>();
        m2.put("date", new Date());
        m2.put("name", "李四");
        m2.put("num", 32);
        data.add(m2);

        for (int i=0; i<data.size(); i++) {
            Map<String, Object> map = data.get(i);
            XSSFRow row = sheet.createRow(i + 1);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue((Date) map.get("date"));

            Cell cell2 = row.createCell(1);
            cell2.setCellValue((String) map.get("name"));

            Cell cell3 = row.createCell(2);
            cell3.setCellValue((Integer) map.get("num"));
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        workbook.close();
        return new ResponseEntity<byte[]>(bos.toByteArray(), responseHeaders, HttpStatus.OK);
    }
Clone this wiki locally