封装 vue 导出 xlsx

这段代码展示了如何使用xhr和相关工具函数实现从指定URL以POST方式导出文件,参数包括URL、请求方法、文件名、参数对象和文件类型。在响应加载后,将转换为Blob并创建一个隐藏的下载链接,触发下载。如果请求失败,会显示错误消息。
摘要由CSDN通过智能技术生成
export function xhrToExportFile(url, method = 'GET', fileName = "文件名称", params = {}, fileType = 'xlsx') {
    const token = getCookie(`PHPSESSID`) || '';
    let xhr = new XMLHttpRequest();
    const hasParams = Object.keys(params).length > 0;
    if (method === 'GET' && hasParams) {
        const keys = Object.keys(params);
        keys.forEach((item, index) => {
            url += `${index === 0 ? '?' : '&'}${item}=${params[item]}`
        })
    }
    xhr.open(method, `${url}`, true);
    xhr.setRequestHeader("phpsessid", token);
    xhr.setRequestHeader('content-type', 'application/json; charset=UTF-8');
    xhr.responseType = "blob";

    xhr.onload = function(e) {
        if (this.status == 200) {
            let blob = this.response;
            let reader = new FileReader();

            reader.readAsDataURL(blob)
            reader.onload = function(e) {
                let a = document.createElement("a");
                a.download = `${fileName}.${fileType}`;
                a.href = e.target.result;
                // 修复firefox中无法触发click
                document.getElementsByTagName('body')[0].append(a);
                a.click();
                a.remove();
            };
        } else {
            xhr.send();
        }
    };
    if (hasParams || method === 'POST') {
        xhr.send(JSON.stringify(params));
    } else {
        xhr.send();
    }
}


import { json2Form,xhrToExportFile } from '@/tools/util';

try {
 xhrToExportFile(exportSpecial, 'POST', '专场信息表', this.ad_form);
} catch (e) {
   this.$message.error(`导出错误:${e}`)
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3中,可以使用 `xlsx` 库来封装导出Excel文件的功能。下面是一个简单的示例,展示了如何使用 `xlsx` 库导出Excel文件。 首先,安装 `xlsx` 库: ```bash npm install xlsx ``` 然后,在需要导出Excel文件的组件中,创建一个方法来封装导出功能: ```javascript // 导入xlsx库 import XLSX from 'xlsx'; export default { methods: { exportToExcel() { // 创建一个工作簿对象 let wb = XLSX.utils.book_new(); // 创建一个工作表对象 let ws = XLSX.utils.json_to_sheet(yourDataArray); // 将工作表添加到工作簿中 XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 将工作簿转换为Excel文件的二进制数据流 let excelData = XLSX.write(wb, { type: 'array', bookType: 'xlsx' }); // 创建一个Blob对象,并将Excel数据流放入其中 let blob = new Blob([excelData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); // 创建一个下载链接,并设置下载属性 let downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(blob); downloadLink.download = 'filename.xlsx'; // 触发点击下载链接 downloadLink.click(); } } } ``` 在上面的代码中,`yourDataArray` 是你要导出的数据数组。你需要将其转换为工作表对象,并添加到工作簿中。然后,将工作簿转换为Excel文件的二进制数据流,最后创建一个下载链接并触发点击,即可下载导出的Excel文件。 请注意,上面的示例代码中的 `filename.xlsx` 是导出的Excel文件的文件名,你可以根据自己的需求修改它。 希望这可以帮助到你!如果你有任何其他问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值