阿里官方使用说明

https://www.yuque.com/easyexcel/doc/write#76fa967c

1、业务逻辑

  1. /**
  2. * excel导出
  3. *
  4. * @param response
  5. * @param basePingyuWords 实体类
  6. * @throws IOException
  7. */
  8. @Override
  9. public void downxlsx(HttpServletResponse response, BasePingyuWords basePingyuWords) throws IOException {
  10. //查询条件
  11. LambdaQueryWrapper<BasePingyuWords> lqw = getLqw(basePingyuWords);
  12. //获取数据
  13. List<BasePingyuWords> list = list(lqw);
  14. if (CollectionUtils.isNotEmpty(list)) {
  15. log.info("导出的数据:{}", list);
  16. //调用封装方法下载xlsx文件
  17. TjFileUtils.downxlsxByEasyexcel(response, BasePingyuWords.class, list);
  18. }
  19. }
  20. /**
  21. * 获取查询条件
  22. *
  23. * @param basePingyuWords
  24. * @return
  25. */
  26. private LambdaQueryWrapper<BasePingyuWords> getLqw(BasePingyuWords basePingyuWords) {
  27. //构造条件构造器
  28. LambdaQueryWrapper<BasePingyuWords> lqw = new LambdaQueryWrapper();
  29. //添加过滤条件
  30. lqw.like(StringUtils.isNotEmpty(basePingyuWords.getShopbelong()), BasePingyuWords::getShopbelong, basePingyuWords.getShopbelong())
  31. .like(StringUtils.isNotEmpty(basePingyuWords.getShortname()), BasePingyuWords::getShortname, basePingyuWords.getShortname());
  32. return lqw;
  33. }

2、easyexcel封装工具类

  1. /**
  2. * 通过EasyExcel导出表格文件(下载失败了会返回一个有部分数据的Excel)
  3. * 1. 创建excel对应的实体对象
  4. * 2. 设置返回的 参数
  5. * 3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
  6. *
  7. * @param response 响应输出
  8. * @param head Java实体类的.class
  9. * @param data 导出data数据
  10. * @throws IOException
  11. */
  12. public static void downxlsxByEasyexcel(HttpServletResponse response, Class head, Collection<?> data) throws
  13. IOException {
  14. //设置返回文件类型
  15. response.setContentType("application/vnd.ms-excel");
  16. //设置编码格式utf-8
  17. response.setCharacterEncoding("utf-8");
  18. response.setHeader("Pragma", "No-cache");
  19. //这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
  20. String fileName = URLEncoder.encode("导出xlsx-" + TjDateUtils.getTodayString(), "UTF-8");
  21. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  22. EasyExcel.write(response.getOutputStream(), head)
  23. .registerWriteHandler(TjEasyExcelCellStyleUtils.getHorizontalCellStyleStrategy()) //设置表格样式
  24. .sheet("sheet1")
  25. .doWrite(data);
  26. }

3、指定导出哪些数据,指定导出列名称

  1. /**
  2. * 用户表字段
  3. */
  4. @Data
  5. @TableName("users")
  6. @ExcelIgnoreUnannotated //只有@ExcelProperty注解的才会导出
  7. public class Users implements Serializable {
  8. private Long id;
  9. @ExcelProperty(value = "帐号") //导出列显示名
  10. @ColumnWidth(10) //列的宽度
  11. private String user_accout;
  12. @ExcelProperty(value = "姓名")
  13. @ColumnWidth(20)
  14. private String user_name;
  15. }

4、做controller接口给前端

  1. /**
  2. * 下载excel文件
  3. *
  4. * @param response HttpServletResponse
  5. * @param basePingyuWords 实体类
  6. */
  7. @GetMapping("/downxlsx")
  8. void downxlsx(HttpServletResponse response, BasePingyuWords basePingyuWords) {
  9. try {
  10. basePingyuWordsService.downxlsx(response, basePingyuWords);
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }

5、前端去POST后端接口,下载文件

  1. // 导出excel信息
  2. //import { downFile } from '@/utils/fileAction.js'
  3. tjdown() {
  4. this.$confirm('确定要导出当前查询的记录吗?', '提示', {
  5. confirmButtonText: '确定',
  6. cancelButtonText: '取消',
  7. type: 'warning',
  8. }).then(async () => {
  9. let res = await this.$api.base.pingyuWordsDown(this.queryInfo)
  10. console.log('res', res);
  11. //获取原始文件的后缀名
  12. let originalFilename = res.fileName
  13. let suffix = originalFilename.substring(originalFilename.lastIndexOf("."))
  14. const strdate = this.$dayjs().format('YYYY-MM-DD')
  15. const filename = `用户表导出-${strdate}${suffix}`
  16. //执行a标签下载
  17. downFile(res.data, filename)
  18. })
  19. },

downFile参考:

  1. // 把后端二进制文件ArrayBuffer下载下来
  2. export function downFile(arrayBuffer, filename) {
  3. // 创建一个临时<a>标签
  4. const link = document.createElement('a')
  5. // 隐藏<a>标签
  6. link.style.display = 'none'
  7. // <a>标签href赋值
  8. link.href = window.URL.createObjectURL(new Blob([arrayBuffer]))
  9. // 设置下载文件名称
  10. link.download = filename
  11. // 追加在body元素里
  12. document.body.appendChild(link)
  13. // 调用单击事件,这里就会触发url下载功能
  14. link.click()
  15. // 移除之前创建的<a>标签
  16. document.body.removeChild(link)
  17. }