简体   繁体   English

如何在 Js 中下载文件?

[英]How to download file in Js?

I am making an api call to export excel file and api is returning the response as encoded zip file like,我正在进行 api 调用以导出 excel 文件,并且 api 将响应作为编码的 ZADCDBD79A192AADC222B 文件返回,例如,

PK-[Content_Types].xmlµSËnÂ0ü•È×*6ôPUCÇ©ô\{“Xø%¯¡ð÷]8”R‰
qòcfgfWöd¶q¶ZCB|ÃÆ|Ä*ð*h㻆},^ê{Va–^K<4lÈfÓÉb+ªõØ°>çø ªœD"xBÚœÌtLˆR-eâv4º*ø>×¹h°éä  Z¹²¹zÜÝé†É­Q2S,±öúH´Þòvà`o"ÞUÏRÙµC(2q†Ãqa9SÝ
& ........... goes on .......

So the above response needs to be converted into downloadable excel file.所以上面的响应需要转换成可下载的excel文件。

For which I have used the following code,为此,我使用了以下代码,

const outputFilename = `${Date.now()}.xls`;
const url = URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', outputFilename);
document.body.appendChild(link);
link.click();

It generate an excel file but when I open the file, it says that the file format is unsupported.它生成一个 excel 文件,但是当我打开文件时,它说文件格式不受支持。

Could you please help me with steps to convert the response data into an real downloadable excel file without issues?您能否帮助我将响应数据转换为真正的可下载 excel 文件而没有问题?

I am using reactjs app for the implementation我正在使用reactjs应用程序进行实施

Thanks in advance.提前致谢。

Try the following example:试试下面的例子:

import React from 'react'
import Button from 'react-bootstrap/Button';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

export const ExportCSV = ({csvData, fileName}) => {

    const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
    const fileExtension = '.xlsx';

    const exportToCSV = (csvData, fileName) => {
        const ws = XLSX.utils.json_to_sheet(csvData);
        const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        const data = new Blob([excelBuffer], {type: fileType});
        FileSaver.saveAs(data, fileName + fileExtension);
    }

    return (
        <Button variant="warning" onClick={(e) => exportToCSV(csvData,fileName)}>Export</Button>
    )
}

Using these deps:使用这些部门:

// install xsls and file-saver // 安装 xsls 和文件保护程序

npm install xlsx file-saver --save

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM