记一次用java导入导出excel遇到的问题

背景:用户有一个excel导入数据,如果有报错或者其他消息需要返回前台一个有这些信息的excel文件的需求。

问题:许久没用过表单就用的ajax,发现能把excel文件以multipart request的方式传到后端controller层处理,但是返回不了前台。后续看了许多文章,才得知ajax的返回值只能是字符流,而导出excel是后台往浏览器中写入二进制的字节流,所以才有下面这种情况,后面用表单进行处理后就可以了。

参考前端js表单提交(上传按钮的点击事件):

        var exportForm = document.forms["ExportForm"];

        // 页面中放置一个隐藏的iframe 处理Form提交结果

        var exportIframe = document.getElementById("ExportFrame");

        if (isAvailable(exportForm)) {
            document.body.removeChild(exportForm); // 清除已有的form表单
        }

        if (isAvailable(exportIframe)) {
            document.body.removeChild(exportIframe); // 移除iframe
        }

        exportIframe = document.createElement("iframe");
        exportIframe.setAttribute("id", "ExportFrame");
        exportIframe.setAttribute("name", "ExportFrame");
        exportIframe.style.display = 'none';
        document.body.appendChild(exportIframe);


        exportForm = document.createElement("form");
        exportForm.setAttribute("id", "ExportForm");
        exportForm.setAttribute("method", "POST");
        // exportForm.setAttribute("target", "_blank");
        exportForm.setAttribute("target", "ExportFrame");
        exportForm.setAttribute("action", "localhost:8080/web/export1");
        exportForm.setAttribute("enctype", "multipart/form-data");

        var inputField = document.createElement("input");
        inputField.setAttribute("type", "file");
        inputField.setAttribute("name", "file");
        inputField.setAttribute("value", $("#articleImageFile")[0].files[0]);
        exportForm.appendChild(inputField);

        var inputField = document.createElement("input");
        inputField.setAttribute("type", "hidden");
        inputField.setAttribute("name", "name");
        inputField.setAttribute("value", "测试哟");
        exportForm.appendChild(inputField);


        document.body.appendChild(exportForm);
        exportForm.submit();

相关参考文章链接:

前端:ajax调用导出数据到excel方法,方法有执行但没有下载_乐事原味~的博客-CSDN博客

java导出excel的两种方式_jiankang66的博客-CSDN博客

SSM中form表单导入excel表后处理并接受回复_雨过山河的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值