第二篇:后端导出 Excel

工作中用到的代码?虽然没能完全理解,但是照猫画虎,相信还是可以的。有不明白的再问问后端,问问大神。(͡° ͜ʖ ͡°)

这种方案需要后端将文件转成 base64 的数据。

相比前端导出,在导出的时候不会导致页面假死(不能操作,影响用户体验),更关键的是速度大大提升,实测3w条数据需要8s左右。

//后端导出 Excel 文件
exportExcel = () => {
    const fetchOption = {
        method: "POST",
        header: {
            "tkUserToken": xxx,
            "userType": "2",
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify(param = ["存放需要传给后端的参数。"])
    }
    const url="http://30.90.100:30303/xxx/xxx...." //地址
    fetch(url, fetchOption).then(response => {
        return response.json();
    }).then(data => {
        const type = "application/vnd.ms-excel";
        const name = "表格的名字.xls"
        this.downloadBase64Blob(data.value, type, name)
    }).catch(() => {
        console.log("下载失败")
    })
}

downloadBase64Blob = (bytes, type, name = "下载") => {
    const blob = this.dataURLtoBlob(`data:${type};base64,${bytes}`)
    const a = document.createElement("a");
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = name;
    window.URL.revokeObjectURL(blob);
    a.remove();
}

dataURLtoBlob = (dataUrl) {
    const arr = dataUrl.split(","), mine = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1])  //atob() 方法用于解码使用 base-64 编码的字符串。
    let n = bstr.length;
    const u8Arr = new Uint8Array(n);
    while (n--) {
        u8Arr[n] = bstr.charCodeAt(n) //charCodeAt() 将字符串转换成unicode编码值
    }
    return new Blob([u8Arr], { type: mine }); //Blob对象可以看作是存放二进制数据的容器
}
posted @ 2019-11-25 19:14  真的想不出来  阅读(948)  评论(0编辑  收藏  举报