springboot整合easyexcel来导出数据

easyexcel是阿里巴巴出品的,导出官方文档地址:Alibaba Easy Excel - 简单、省内存的Java解析Excel工具 | 写Excel

下面通过实例来演示导出数据demo

首先新建一个springboot项目(这里不再赘述)

然后在pom里面引入easyExcel的依赖:

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

然后直接展示业务逻辑的关键代码:

    public void exportData(HttpServletResponse response) {

        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // URLEncoder.encode可以防止中文乱码
        String fileName= null;
        try {
            fileName = URLEncoder.encode("has测试下载","UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
        // 查询数据信息
        List<User> userList=exportMapper.queryAllData();
        //将User映射为导出的实体类
        List<UserExcel> userExcelList=new ArrayList<>();
        for (User user:userList){
            UserExcel userExcel=new UserExcel();
            BeanUtils.copyProperties(user,userExcel);
            userExcelList.add(userExcel);
        }
        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(),UserExcel.class).sheet("名单信息(sheet名称)").doWrite(userExcelList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

注意:代码中有一点就是将User转为UserExcel,这是因为在使用easyExcel导出数据的时候需要有一个实体类来和excel中的字段进行映射,由于需要在实体类中设置excel的属性,所以另起一个实体类来封装导出的excel的字段比较合适。

UserExcel:

@Data
public class UserExcel {
    /**
     * index指定在excel中列数
     */
    @ExcelProperty(value = "序号" ,index = 0)
    private int id;

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

    @ExcelProperty(value = "年龄" ,index = 2)
    private int age;

    @ExcelProperty(value = "省份" ,index = 3)
    private String province;

    @ExcelProperty(value = "城市" ,index = 4)
    private String city;

    @ExcelProperty(value = "地址" ,index = 5)
    private String address;

    @ExcelProperty(value = "爱好" ,index = 6)
    private String hobby;
}

代码写完启动服务通过浏览器访问地址:http://localhost:8888/exportData

导出的excel的信息如下:

而我数据库中的信息如下所示:

 

可以发现导出的数据是正常的,导出功能完成,相关的整个demo的代码已经上传到csdn,有需要的可以下载,下载地址:演示通过easyExcel来导出excel数据-Java文档类资源-优快云下载

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酒书

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值