reol44 2022-05-23 22:13 采纳率: 40%
浏览 384
已结题

js实现Post导出excel乱码

问题描述

给自己的web系统写了个导出表格excel文件的代码,用到是ajax请求post方法的接口,返回后对其response保存为xls文件,但是保存后一直是乱码的,显示格式错误,使用postman测试了导出接口,发现是没有问题的,直接send and download可以下载正确的xls文件

源代码

js部分 请求接口,创建url,下载

这个代码是网上抄过来改的,确实能post触发下载,也下载到了文件,就是文件格式不太对劲

$.ajax({
    type: 'post',
    url: window.BASE_URL + window.paths.userListXls,
    data: JSON.stringify({
        filtrate: {
            limit,
            offset,
            ...filtrate
        },
        dictionary,
        sheetName: sheetName,
    }),
    contentType: "application/json;charset=UTF-8",
    responseType: 'blob'
}).then((res, statusTest, xhr) = >{
    window.xhrr = xhr;
    console.log(xhr, res == xhr.responseText) let disposition = xhr.getResponseHeader("Content-Disposition");
    let fileName = disposition.slice(disposition.indexOf("fileName=") + 9);
    const blob = new Blob([res], {
        type: "application/vnd.ms-excel;charset=utf-8"
    });
    // 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
    const elink = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink);
})

java后台

@RequestMapping(value = "/xls/export", method = RequestMethod.POST)
public @ResponseBody 
String excelExportHandle(HttpServletRequest req, HttpServletResponse res) {
    try {
        ExportGuide guide = (ExportGuide) req.getAttribute("guide");
        // 数据
        JSONArray data = (JSONArray) req.getAttribute("data");
        ServletOutputStream out = res.getOutputStream();
        try {
            res.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(guide.getFileName() + guide.getType().getSuffix(), "UTF-8"));
            res.setContentType("application/vnd.ms-excel;charset=utf-8");
        } catch(UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        // 数据转换成workbook
        Workbook workbook = ExcelUtils.listToXls(guide.getFileName(), data, ExcelUtils.getDictionary(guide.getDictionary()), guide.isHasHeader());
        workbook.write(out);
        out.flush();
        out.close();
        return null;
    } catch(Exception e) {
        e.printStackTrace();
        return "fail";
    }
}
  • 写回答

1条回答 默认 最新

报告相同问题?

问题事件

  • 系统已结题 6月1日
  • 已采纳回答 5月24日
  • 创建了问题 5月23日

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装