SpringBoot使用easyexcel导出Excel

引入依赖

        <!--easyexcel,推荐使用2.0 以上版本,功能更加完善-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.6</version>
        </dependency>

创建模板VO类

 @ExcelProperty(value = "导出excel表头的标题")

@ExcelIgnore:忽略这个字段,不导出这个字段的数据

@Data
public class UserExcelVo {

    @ExcelProperty(value = "姓名")
    private String username;

    @ExcelProperty(value = "手机号")
    private String mobile;

    @ExcelProperty(value = "创建时间")
    private String saveDate;

    /**
     * 忽略这个字段
     */
    @ExcelIgnore
    private String ignore;

}

最好都是用String类型接收数据,接收到后另做转换

导出

    /**
     * 导出用户模板
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/fileOutExcel", method = {RequestMethod.POST, RequestMethod.GET})
    public void fileOutExcel(HttpServletResponse response) throws Exception {

        List<UserExcelVo> vos = new ArrayList<>();
        
        UserExcelVo userExcelVo= new UserExcelVo();
        userExcelVo.setUserName("张三");
        userExcelVo.setMobile("15600000000");
        userExcelVo.setSaveDate("2022.02.22 22:22");
        
        vos.add(userExcelVo);
        
        ExcelWrite.webWrite(response, "用户模板", UserExcelVo.class, "sheet1", vos );
    }

工具类

public class ExcelWrite {

   /**
     * 单sheet下载
     *
     * 文件下载并且失败的时候返回json(默认失败了会返回一个有部分数据的Excel)
     *
     * @since 2.1.1
     */
    public static  <T> void webWrite(HttpServletResponse response, String fileName, Class c, String sheetName, List<T> data) throws IOException {
        // 这里注意 有反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), c).autoCloseStream(Boolean.FALSE).sheet(sheetName)
                    .doWrite(data);
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("code", "11");
            map.put("msg", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一个肥鲶鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值