easyexcel导出文件(多个sheet导出)

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
        </dependency>

单个sheet

@RequestMapping("/excelTest")
    public void excelTest(HttpServletResponse response) throws Exception{
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        responseHeader(response,"模板");
        EasyExcel.write(response.getOutputStream(), ExcelEntity.class).sheet("事件").doWrite(data());
    }
private static List<ExcelEntity> data() {
        List<ExcelEntity> list = new ArrayList<ExcelEntity>();
        for (int i = 0; i < 10; i++) {
            ExcelEntity data = new ExcelEntity();
            data.setId(i);
            data.setAmount(new BigDecimal(i));
            data.setAmountRate(new BigDecimal(i));
            list.add(data);
        }
        return list;
    }
    //封装响应流
    public static void responseHeader(HttpServletResponse response, String name) throws UnsupportedEncodingException {
        String fileName = name;
        String encodeName = java.net.URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodeName + ".xlsx");
        response.setHeader("Access-control-Expose-Headers", "attachment");
    }

实体类

public class ExcelEntity implements Serializable {

    @ExcelProperty(value = "主键id")
    private Integer id;
    @ExcelProperty(value = "金额")
    @NumberFormat("###.##")
    private BigDecimal amount;
    @ExcelProperty(value = "百分比")
    @NumberFormat("###.##%")
    private BigDecimal amountRate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public BigDecimal getAmountRate() {
        return amountRate;
    }

    public void setAmountRate(BigDecimal amountRate) {
        this.amountRate = amountRate;
    }
}

多个sheet

@RequestMapping("/excelTest")
    public void excelTest(HttpServletResponse response) throws Exception{
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        responseHeader(response,"模板");
        WriteTable writeTable = EasyExcel.writerTable(1).needHead(Boolean.TRUE).head(ExcelEntity.class).build();
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = new WriteSheet();
        writeSheet.setSheetNo(1);
        writeSheet.setSheetName("aa");
        excelWriter.write(data(),writeSheet,writeTable);
        writeSheet = new WriteSheet();
        writeSheet.setSheetNo(2);
        writeSheet.setSheetName("bb");
        excelWriter.write(data(),writeSheet,writeTable);
        excelWriter.finish();
    }
经验分享 程序员 微信小程序 职场和发展