介绍

EasyExcel出Java处理Excel一个优秀的库

依赖:

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

Web使用

@PostMapping("/download/ResellerList")
@Operation(summary = "运营端-下载代理商列表") // 返id
public void downloadResellerList(
        @YPHCurrentAdmin YPHAdminInfo adminInfo, @RequestBody ResellerQryArgVO argV0,
        HttpServletResponse response) throws IOException {
    // 查询数据相关
    ResellerQueryQry qry = argV0.toqry(argV0);
    ResellerPageBO resellerPageBO = resellerQueryService.getResellerList(qry);

    // 通过 mapStruct 进行转换
    List<ResellerAgentQryResultExcelVO> resultList = ResellerAgentQryResultExcelVO.fromBO(
            resellerPageBO);
    // 保存时的文件名字
    String fileName = "代理商列表.xlsx";
    // 设置响应头
    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
    response.setCharacterEncoding(StandardCharsets.UTF_8.name()); // 字符集编码
    response.setContentType("application/octet-stream"); // 返回内容的MIME类型
    response.addHeader("Content-disposition", "attachment;filename=" + fileName + ";filename*=UTF-8" + fileName);
    // 写入Excel流
    EasyExcel.write(response.getOutputStream(), ResellerAgentQryResultExcelVO.class)
             .sheet("sheet1").doWrite(resultList);
}

导出为文件

  1. 如果运行报错,在VM option 添加--add-opens java.base/java.lang=ALL-UNNAMED
  2. 如果没有数据,MyUserVO 对象中属性是否是小写
package com.lucas.flexible;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.Data;

import java.util.ArrayList;

@Data
class MyUserVO {
    @ExcelIgnore
    private Integer id;

    @ExcelProperty("姓名")
    @ColumnWidth(20)
    // 必须小写
    private String name; // 登录账号-手机号

    @ExcelProperty("描述")
    @ColumnWidth(20)
    private String desc; // 企业名称-代理商名称
}

public class TestExcel {
    public static void main(String[] args) {
        MyUserVO vo = new MyUserVO();
        vo.setId(12);
        vo.setName("xiaoming");
        vo.setDesc("happy");
        ArrayList<MyUserVO> list = new ArrayList<>();
        list.add(vo);
        EasyExcel.write("demo.xlsx", MyUserVO.class).sheet().doWrite(list);
    }
}