spring boot + easypoi快速實現excel匯入匯出

阿平發表於2019-01-19

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

就這樣就可以非常快速的實現一個excel匯出了,還有很多好用的功能可以看官網。

相關文章