关于前端:文件流方式导出Excel表格

24次阅读

共计 775 个字符,预计需要花费 2 分钟才能阅读完成。

之前做的我的项目都是在不调用后盾接口的状况下,将 json 数据导出到 excel 表格,纯前端去实现导出 Excel
最近做的我的项目,须要向后盾传递不同的参数值,后盾查问出符合条件的数据,以文档流的格局返回前端,前端再导出为 Excel。

调用后端接口,返回的是如下的文件流

此时前端须要把查问到的数据导出为 excel 格局

// 导出 Excel
getExcel() {
    const url = '你的 URL';
    this.$http.post(url, params, {responseType: 'blob'}).then(res => {let blob = new Blob([res.data], {type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
        if (window.navigator.msSaveOrOpenBlob) {navigator.msSaveBlob(blob);
        } else {let elink = document.createElement('a');
            elink.download = "报表.xls";
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
        }
    }).catch(err => {console.warn(err);
    });
},

留神:在申请接口的时候肯定要设置 –> responseType: 'blob'
具体可参考 MDN 文档:https://developer.mozilla.org…

正文完
 0