如何在客户端将数据导出和下载为有效的xlsx格式?



从后端 api 中,我将学生数据列表获取到一个有效的 excel 文件中,该文件在到达端点/api/v1.0/students/students-xlsx/时被下载,但在客户端,当我调用这个端点时,它显示不可读的格式并被下载为损坏的 excel 文件。

我遵循了一些堆栈溢出建议,例如 atob,对响应数据进行编码 URI 并添加特定类型 (UTF-8(,但它失败了。我仍然得到带有奇怪字符的损坏文件。

excelFileDownload() {
this.$http.get(this.exportXLUrl)
.then((response) => {
response.blob().then(() => {
const blob = new Blob([response.body], { type: response.headers.get('content-type') });
const filename = response.headers.map['content-disposition'][0].split('filename=')[1];
const link = document.getElementById('download-excel-file');
link.href = window.URL.createObjectURL(blob);
link.download = filename.split('"').join('');
link.style.display = 'block';
link.click();
});
});
},

我希望输出与我仅使用可浏览 API 调用端点时相同 - 这为我提供了具有可读字符的适当 xls 格式文件。但在客户端,我根本不明白这一点。一切都坏了。任何帮助将不胜感激,以改进我的代码。

如果你愿意使用XMLHttpRequest

(未经测试(

const xhr = new XMLHttpRequest();
xhr.open('GET', this.exportXLUrl, true);
xhr.responseType = 'blob';
xhr.addEventListener('load', () =>
{
if(xhr.status == 200)
{
const url = window.URL.createObjectURL(xhr.response);
const contentDisposition = xhr.getResponseHeader('content-disposition');
const filename = /filename=([^;]*)/.exec(contentDisposition)[1];
const link = document.getElementById('download-excel-file');
link.href = window.URL.createObjectURL(blob);
link.download = filename.split('"').join('');
link.style.display = 'block';
link.click();
//Dont forget to revoke it
window.URL.revokeObjectURL(url);
}
else
{
//error
}
});
xhr.addEventListener('error', err =>
{
//error
});
xhr.send();

我需要在标头和响应类型中传递内容类型以及获取请求,如下所示:

headers: { 'Content-Type': 'application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet' },
responseType: 'arraybuffer'

它现在工作正常。

最新更新