1. 程式人生 >實用技巧 >其它 >使用EasyExcel返回檔案流,匯出excel

使用EasyExcel返回檔案流,匯出excel


背景

在j專案開發中經常會有匯出檔案excel的需求,對此EasyExcel是個非常好用的工具,官方羽雀文件地址https://www.yuque.com/easyexcel/doc/easyexcel,這裡簡單總結一下使用該工具返回檔案流的操作。

1.引入依賴

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

2.新增匯出資料模板類(這裡也可以直接使用excel檔案作為匯出模板,這裡不做介紹)

例如這兒新增一個StudentModel類,每個欄位需要新增@ExcelProperty註解,@ColumnWidth(15)可以指定列寬

@Data
public class SentimentInfoListModel {

    @ExcelProperty(value = "年齡",index = 0)
    private Integer age;

    @ExcelProperty(value = "名字",index = 1)
    private String name;

    @ColumnWidth(15)
    @ExcelProperty(value = "性別",index = 2)
    private String sex;
}

3.構造模板資料,返回檔案流

  @GetMapping("student")
  public void export( HttpServletResponse response, @RequestParam("fileName") String fileName) {
            //呼叫業務,構造模板列表資料
            List<StudentModel> listModel = ......;
            //寫入資料
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            //使用的easyexcel工具就這一行
            EasyExcel.write(out, SentimentInfoListModel.class).autoCloseStream(true).sheet("資訊列表").doWrite(listModel);
            out.flush();
    }

最後訪問該請求,就可得到相應excel檔案。