EasyExcel 导出工具

本文介绍了如何在SpringMVC项目中使用EasyExcel库进行数据的分页导出,包括添加依赖、创建实体类、配置控制器以及处理文件名编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write

Pom 引入

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>21.0</version>
</dependency>

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

EasyExcel 使用(Web)

实体类

  • 注解ExcelProperty :标注name字段的excel列名
@Data
public class DemoData {
    @ExcelProperty("姓名")
    private String name;

    @ExcelProperty("年龄")
    private String age;
}

controller

@Controller
public class ExcelUtils {

    @GetMapping("download")
    public void download(HttpServletResponse response) {
        String fileName = encodeFileName("fileName");
        String sheetName = "sheetName";

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
		// 分页导出数据
        List<DemoData> data = data();
        Lists.partition(data, 200).forEach(subData -> {
            try {
                EasyExcel.write(response.getOutputStream(), DemoData.class)
                        .sheet(sheetName)
                        .doWrite(subData);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private String encodeFileName(String fileName) {
        try {
            // 这里URLEncoder.encode可以防止中文乱码
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fileName;
    }
	
	// 读取数据
    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<>();
        DemoData demoData = new DemoData();
        demoData.setName("name");
        demoData.setAge("18");
        list.add(demoData);
        return list;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值