欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot + easypoi快速实现excel导入导出

程序员文章站 2024-03-21 20:12:22
...

easypoi封装了poi让我们能够非常简单的实现Excel导出,Excel模板导出,Excel导入,Word模板导出等,具体可见官网:http://www.afterturn.cn/

我这边实现了一个excel的导出,记录一下。

1、pom文件引入starter

<dependency>
   <groupId>cn.afterturn</groupId>
   <artifactId>easypoi-spring-boot-starter</artifactId>
   <version>3.2.0</version>
</dependency>

2、定义需要导出的对象DTO

@Table(name = "ORDERS")
public class OrderExcelDto{

    @Excel(name = "ORDER_ID", width = 25,orderNum = "0")
    private String orderId;

    @Excel(name = "CREATE_TIME",width = 20,exportFormat = "yyyy-MM-dd HH:mm:ss", orderNum = "1")
    private Date createTime;

    @Excel(name = "STATUS",width = 20,replace = {"created_01", "payment_02","used_03","time out_04"}, orderNum = "2")
    private String status;

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

具体语义如下,详情可见官网

name:列明;replace:前者是最后替换的值,后者是数据库的值;exportFormat:导出的时间格式,以这个是否为空来判断是否需要格式化日期;width:列宽等

3、将查询的sql映射到上述的DTO,然后通过starter中提供工具类做导出操作

@GetMapping("/orderExport")
    public void orderExport(HttpServletResponse response) throws Exception {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=orders.xls");
        List<OrderExcelDto> list = orderService.queryOrderExcel();
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),OrderExcelDto.class,list);
        workbook.write(response.getOutputStream());
    }

4、前台js中可以直接定义事件触发上述get请求

function  export() {
    document.location.href = host+"/orderExport";
}

最后就可以验证一下了,如果有问题可以邮件我。