Vue2 导出Excel + 解决乱码问题 —— axios (下载后台传过来的流文件(excel)后乱码问题)

本文介绍了在前端开发中导出Excel数据的三种方法:使用js-file-download插件、利用Blob对象以及通过axios发送post请求并处理返回的文件流。每种方法都详细解释了其实现步骤和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:是用了插件 https://github.com/kennethjiang/js-file-download

方法二:是用了 blob

  //      导出Excel
   exportBill: function () {
 
     let url_post = Vue.prototype.api.apiList.EXPORT_BILL; //请求地址
 
     let params_post = { //参数
       orderStartDate: this.timepickerDateFormat(this.rangeTime[0]) || this.rangeTime[0] || '',
       orderEndDate: this.timepickerDateFormat(this.rangeTime[1]) || this.rangeTime[1] || '',
       prodCode: this.prodId,
       promoteFlag: this.promotionSiteId,
       policyStatusList: this.tableBillStateCheckedData,
     };
 
     Vue.axios.post(url_post, params_post, {
       responseType: 'arraybuffer'
     }).then((res) => {
 
       let fileName = res.headers['content-disposition'].match(/fushun(\S*)xls/)[0];
 
       fileDownload(res.data, fileName); //如果用方法一 ,这里需要安装 npm install js-file-download --save ,然后引用 var fileDownload = require('js-file-download'),使用详情见github;
              // let blob = new Blob([res.data], {type: "application/vnd.ms-excel"}); 
 
              // let objectUrl = URL.createObjectURL(blob); 
 
              // window.location.href = objectUrl;  
 
     }).catch(function (res) {});

方法三(附加):

1、接口要求: post方法、入参为json格式、出参文件流

* 2、axios:设置返回数据格式为 blob 或者 arraybuffer   ( 注意 )

   axios({ // 用axios发送post请求
     method: 'post',
     url: ' /serviceTime/exportData', // 请求地址
     data: form, // 参数
     responseType: 'blob', // 表明返回服务器返回的数据类型
     headers: {
       'Content-Type': 'application/json'
     }
   }).then(res => { // 处理返回的文件流
     const blob = new Blob([res.data]);//new Blob([res])中不加data就会返回下图中[objece objece]内容(少取一层)
     const fileName = '统计.xlsx';//下载文件名称
     const elink = document.createElement('a');
     elink.download = fileName;
     elink.style.display = 'none';
     elink.href = URL.createObjectURL(blob);
     document.body.appendChild(elink);
     elink.click();
     URL.revokeObjectURL(elink.href); // 释放URL 对象
     document.body.removeChild(elink);
   })
### Vue 前端导出 Excel 乱码解决方案 当遇到从 PHP 结合 Vue 导出 Excel 文件时出现乱码的情况,通常是因为编码处理不当造成的。尽管读取的文件是以 UTF-8 编码保存,在某些情况下,浏览器下载后的文件可能无法正确显示字符。 #### 设置正确的响应头和 MIME 类型 确保服务器端设置恰当的内容类型非常重要。无论后端返回的是 `application/vnd.ms-excel` 或者 `application/octet-stream`,这主要影响到客户端如何解析接收到的数据[^3]。为了使大多数现代浏览器能够识别并正确处理这些二进制数据作为电子格文件,建议使用后者即八位字节流的形式发送给前端应用。 #### 处理 Axios 请求中的 Blob 数据 在通过 Axios 发起 HTTP POST 请求获取 Excel 文件时,应该显式指明期望接收 blob 格式的响应体: ```javascript import axios from 'axios'; import qs from 'qs'; function post(url, data, options) { const axiosOption = { method: 'post', url, data: qs.stringify(data), responseType: 'blob' // 明确指出我们希望得到的是一个Blob对象而不是默认字符串形式 }; if (options && options.responseType === 'blob') { axiosOption.responseType = 'blob'; // 如果传入了额外option参数,则再次确认responseType属性值为'blob' } return new Promise((resolve, reject) => { axios(axiosOption).then(response => resolve(response.data)).catch(error => reject(error)); }); } ``` 这段代码片段展示了如何配置 Axios 来接受来自服务端的二进制大对象(BLOB),从而避免因不适当转换而导致的信息丢失或损坏[^4]。 #### 下载链接创建与 BOM 插入 为了让最终用户可以顺利地点击按钮触发下载操作而不必担心兼容性问题,可以通过 JavaScript 动态生成 `<a>` 元素来实现这一点,并且考虑到一些特定版本 Office 对于无BOM标记UTF-8文档的支持不佳,可以在实际写入之前向内容前附加 Byte Order Mark(BOM),以帮助应用程序理解所使用的字符集: ```javascript // 创建隐藏的<a>标签用于触发下载动作 const linkElement = document.createElement('a'); linkElement.style.display = 'none'; document.body.appendChild(linkElement); async function downloadFile(fileName, content) { try { // 添加BOM至content头部 const utf8WithBom = new Uint8Array([0xEF, 0xBB, 0xBF]); const combinedContent = new Blob([utf8WithBom, content], { type: 'application/octet-stream;charset=utf-8;' }); // 构建URL指向该Blob资源 linkElement.href = URL.createObjectURL(combinedContent); linkElement.download = fileName; // 执行点击事件模拟用户交互行为完成下载过程 linkElement.click(); // 清除临时创建的对象释放内存空间 setTimeout(() => { window.URL.revokeObjectURL(linkElement.href); document.body.removeChild(linkElement); }, 100); } catch (error) { console.error(`Failed to create and trigger file download`, error); } } downloadFile('example.xlsx', await post('/api/export/excel')); ``` 此方法不仅解决了由于缺少必要的元数据而引起的潜在乱码现象,还提高了用户体验的一致性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值