springboot实现导出excel

  1. 添加maven依赖
  2. 编写要导出的类
  3. 去数据库查询要导出的数据
  4. 调用接口导出数据

添加maven依赖

  <!-- 导出excel       -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.5</version>
        </dependency>

编写导出的excel的表的实体类


import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode
public class AddMoney {
    @ExcelProperty("用户")
    private String username;
    @ExcelProperty("充值时间")
    private String date;
    @ExcelProperty("充值金额")
    private int usermoney;
}

编写使用mybatis-plus到数据库中查询表

 private List<AddMoney> getAddMoney() {
        List<Changemoney> AddMoney = changemoneyService.exportexcelChangeMoney();
        List<AddMoney> list = ListUtils.newArrayList();
        for (int i = 0; i < AddMoney.size(); i++) {
            AddMoney data = new AddMoney();
            data.setUsername(AddMoney.get(i).getUsername());
            data.setDate(AddMoney.get(i).getCreatedate());
            data.setUsermoney(AddMoney.get(i).getAddmoney());
            list.add(data);
        }
        return list;
    }

编写接口并调用

    @GetMapping("exportExcelAddMoney")
    public void exportExccelAddMoney(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("充值情况", "UTF-8").replaceAll("\\+", "%20");
        List<AddMoney> list = getAddMoney();
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(),
                AddMoney.class).sheet("充值情况").doWrite(list);

    }

实操测试 点击链接会实现导出excel的功能
http://162.14.107.118:8086/PC/exportExcelAddMoney

你可能感兴趣的:(Java,spring,boot,excel,后端)