详解ajax实现excel报表导出


当前第2页 返回上一页

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

import cn.afterturn.easypoi.excel.ExcelExportUtil;

import cn.afterturn.easypoi.excel.entity.ExportParams;

 

@PostMapping(value = "/download")

public void downloadList(@RequestBody Objct obj, HttpServletResponse response) {

 

 ......

 

 List<Custom> excelList = new ArrayList<>();

  

   // excel总体设置

   ExportParams exportParams = new ExportParams();

   // 指定sheet名字

   exportParams.setSheetName("test");

   Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Custom.class, excelList);

  

   response.setContentType("application/vnd.ms-excel");

   response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test", "utf-8") + ".xls");

   OutputStream outputStream = response.getOutputStream();

   workbook.write(outputStream);

   outputStream.flush();

   outputStream.close();

    

 ......

  

}

测试结果

excel能正常导出,但下载下来的excel全是乱码。经过各种找答案,整理了一下可能是以下原因导致:

1、后端未设置字符集,或者在spring框架的过滤器中统一设置了字符集;
2、前端页面未设置字符集编码;
3、需要在ajax中添加 request.responseType = “arraybuffer”;

经过不断测试,我的应该是第三点导致。但在jquery ajax 中添加后仍然不起作用,乱码问题始终无法解决。

第二版

主要代码

前端,使用原生的ajax。后端未变动。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

var xhr = new XMLHttpRequest();

xhr.responseType = "arraybuffer";

xhr.open("POST", url, true);

xhr.onload = function () {

 const blob = new Blob([this.response], {type:"application/vnd.ms-excel"});

 if(blob.size < 1) {

  alert('导出失败,导出的内容为空!');

  return;

 }

 if(window.navigator.msSaveOrOpenBlob) {

  navigator.msSaveOrOpenBlob(blob, 'test.xls')

 } else {

  const aLink = document.createElement('a');

  aLink.style.display = 'none';

  aLink.href = window.URL.createObjectURL(blob);

  aLink.download = 'testxls';

  document.body.appendChild(aLink);

  aLink.click();

  document.body.removeChild(aLink);

  return;

 }

}

xhr.setRequestHeader("Authorization", "xxx");

xhr.setRequestHeader("Content-Type", "application/json");

xhr.send(JSON.stringify(queryParams));

测试结果

下载的excel不再乱码,原生ajax中使用 “arraybuffer” 使用是生效的。

总结

“arraybuffer” 这个参数导致的excel导出乱码,在原生的ajax中设置是有效的,在jquery的ajax中暂时还没找到生效的方式。

以上就是详解ajax实现excel报表导出的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

ajax请求方式有几种

ajax获取网页添加到div中的方法

如何实现ajax请求?

jquery和ajax是什么?

jquery中ajax提交数据乱码怎么办

javascript介绍ajax加载单张图片展示进度的方法

ajax实现下载进度条的示例代码

ajax和javascript之间有什么区别

ajax 如何实现 excel 报表导出?

实例讲解jquery与js实现ajax

更多相关阅读请进入《excel报表》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...