java导出文件流并下载

23 篇文章 0 订阅
20 篇文章 1 订阅

用户需求:

向后台请求操作时,需要同时返回响应错误文档(excel文档),以及弹出错误提示。

ok!ok!ok!直接上代码
Java后端代码

    @ApiOperation(value = "接口返回的类型是json格式,里面字段对应base64格式的excel文件", notes = "接口返回的类型是json格式,里面字段对应base64格式的excel文")
    @RequestMapping(value = "exportDemo")
    public Map exportDemo() throws Exception {
        Map map = new HashMap();
        map.put("success", false);
        map.put("message", "导入失败");
        HSSFWorkbook errWorkbook = new HSSFWorkbook(); //创建Excel
        HSSFSheet sheet = errWorkbook.createSheet("Sheet1");//创建Sheet
        HSSFRow T_row = sheet.createRow(0);//创建一行表头
        T_row.createCell(0).setCellValue("必填,学号");//设置表头列名
        T_row.createCell(1).setCellValue("学生姓名");//设置表头列名
        T_row.createCell(2).setCellValue("培养单位");//设置表头列名
        T_row.createCell(3).setCellValue("必填,主导师工号");//设置表头列名
        T_row.createCell(4).setCellValue("主导师姓名");//设置表头列名
        T_row.createCell(5).setCellValue("联合导师工号(如有)");//设置表头列名
        T_row.createCell(6).setCellValue("联合导师姓名(如有)");//设置表头列名
        T_row.createCell(7).setCellValue("错误信息");//设置表头列名
        HSSFCellStyle style = errWorkbook.createCellStyle();
        style.setDataFormat(errWorkbook.createDataFormat().getFormat("@")); // 设置为文本格式
        for (int i = 0; i < T_row.getPhysicalNumberOfCells(); i++) {
            sheet.setDefaultColumnStyle(i, style);
        }
        for (Cell cell : T_row) {
            cell.setCellStyle(style);
            cell.setCellType(CellType.STRING);
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 将EXCEL文件写进流内
        errWorkbook.write(byteArrayOutputStream);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        String base64ExlCode = Base64Utils.encodeToString(bytes);
        map.put("excel",base64ExlCode);
        return map;
    }

前端代码

        ,exportDemo:function() {
            var self = this
            var url =  baseUrl +  self.QUERY_URL +'/exportDemo';
            //定义参数
            var myform = new FormData();
            $.ajax({
                url:url,
                data:myform,
                dataType: "json",
                type: 'post',
                async: true,
                //重要,必须设置 false
                contentType: false,
                //重要,必须设置 false
                processData: false,
                beforeSend: function () {
                    self.$Spin.show();
                },
                complete: function () {

                },
                success: function (res) {
                    alert(res.message)
                    //下载文件
                    var blob = self.dataURLtoBlob(res.excel);
                    var downloadUrl = window.URL.createObjectURL(blob);
                    var anchor = document.createElement("a");
                    anchor.href = downloadUrl;
                    anchor.download = decodeURI("导入错误.xls");
                    anchor.click();
                }
                ,error : function (data){
                    self.$Spin.hide();
                    self.$Message.error({content:data.responseText,duration: 5,background: true});
                }
            })
        }
        // 核心 将base64的字符串转为文件流
        ,dataURLtoBlob:function(base64Str) {
            var bstr = atob(base64Str);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            // 下载的是excel格式的文件
            return new Blob([u8arr], { type: "application/vnd.ms-excel" });
            //其他类型:
            // 'doc' => 'application/msword',
            // 'bin' => 'application/octet-stream',
            // 'exe' => 'application/octet-stream',
            // 'so' => 'application/octet-stream',
            // 'dll' => 'application/octet-stream',
            // 'pdf' => 'application/pdf',
            // 'ai' => 'application/postscript',
            // 'xls' => 'application/vnd.ms-excel',
            // 'ppt' => 'application/vnd.ms-powerpoint',
            // 'dir' => 'application/x-director',
            // 'js' => 'application/x-javascript',
            // 'swf' => 'application/x-shockwave-flash',
            // 'xhtml' => 'application/xhtml+xml',
            // 'xht' => 'application/xhtml+xml',
            // 'zip' => 'application/zip',
            // 'mid' => 'audio/midi',
            // 'midi' => 'audio/midi',
            // 'mp3' => 'audio/mpeg',
            // 'rm' => 'audio/x-pn-realaudio',
            // 'rpm' => 'audio/x-pn-realaudio-plugin',
            // 'wav' => 'audio/x-wav',
            // 'bmp' => 'image/bmp',
            // 'gif' => 'image/gif',
            // 'jpeg' => 'image/jpeg',
            // 'jpg' => 'image/jpeg',
            // 'png' => 'image/png',
            // 'css' => 'text/css',
            // 'html' => 'text/html',
            // 'htm' => 'text/html',
            // 'txt' => 'text/plain',
            // 'xsl' => 'text/xml',
            // 'xml' => 'text/xml',
            // 'mpeg' => 'video/mpeg',
            // 'mpg' => 'video/mpeg',
            // 'avi' => 'video/x-msvideo',
            // 'movie' => 'video/x-sgi-movie',
        }

请求后,响应如下

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

D哈迪斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值