Springboot通过前端发起请求,拿到数据库中的数据并生成excel表格,postman请求并下载文件

本文介绍了在SpringBoot3.2.0版本项目中,如何使用MyBatisPlus3.5.4.1和EasyExcel3.3.3进行数据操作,特别关注了实体类中枚举类型的转换问题以及Controller层的Excel文件导出功能。
摘要由CSDN通过智能技术生成

springboot版本3.2.0,数据库版本8

mybatisplus版本3.5.4.1

依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.3</version></dependency>
实体类

实体类中的枚举类型转换,因调用方法后还是不能转换类型所以暂未解决

public class User {
    @ExcelProperty("用户编号")
    @ColumnWidth(20)
    private Long id;

    @ExcelProperty("姓名")
    @ColumnWidth(20)
    private String username;

    @ExcelProperty("密码")
    @ColumnWidth(20)
    private String password;

    @ExcelProperty("用户电话")
    @ColumnWidth(20)
    private String phone;

    @ExcelProperty("用户信息")
    @ColumnWidth(20)
    private String info;

    //@ExcelProperty(value = "用户状态",converter = UserStatusConverter.class)
    @ExcelIgnore
    @ColumnWidth(20)
    private UserStatus status;

    @ExcelProperty("用户金额")
    @ColumnWidth(20)
    private Integer balance;

    @ExcelProperty("用户创建时间")
    @ColumnWidth(20)
    private LocalDateTime createTime;

    @ExcelProperty("用户更新时间")
    @ColumnWidth(20)
    private LocalDateTime updateTime;
Controller层
  @GetMapping("/user")
    public void exportUserExcel(HttpServletResponse response){
        try{
            this.setExcelResponseProp(response,"用户列表");
            List<User> userList =userService.listAllUsers(new User());
            EasyExcel.write(response.getOutputStream())
                    .head(User.class)
                    .excelType(ExcelTypeEnum.XLS)
                    .sheet("用户列表")
                    .doWrite(userList);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        }

    /**
     * postman测试
     * @param response
     * @param rawFileName
     * @throws UnsupportedEncodingException
     */
    private  void setExcelResponseProp(HttpServletResponse response,String rawFileName) throws UnsupportedEncodingException{
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        }
postman测试

Excel表格

获取数据成功

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值