使用 ReactJS 中的 FileSaver 从 API 请求保存 Excel 文件

Tib*_*ibo 5 reactjs filesaver.js

在我的 React 应用程序中,我正在查询 API 以检索 Excel 格式的数据库导出。该调用是在我的传奇中执行的。然后我尝试使用 FileSaver 保存 API 的响应

const {headers, data} = response;
FileSaver.saveAs(new Blob([data], {type: headers['content-type']}), filename);
Run Code Online (Sandbox Code Playgroud)

响应的标题如下

{
    content-disposition: "attachment; filename="export.xlsx"; filename*=utf-8''export.xlsx;",
    content-type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
Run Code Online (Sandbox Code Playgroud)

当我使用 Postman 调用 API 并保存文件时,我可以像任何标准 Excel 文件一样打开它。但是当我用 FileSaver 保存它时,我无法打开它。它只是十六进制编码。我缺少什么才能以正确的方式保存文件?

ise*_*noe 0

如果数据是数据框,您可以使用 Danfo.js:

https://danfo.jsdata.org/api-reference/input-output/danfo.to_excel

const dfd = require("danfojs-node")

let data = {
    Abs: [20.2, 30, 47.3],
    Count: [34, 4, 5],
    "country code": ["NG", "FR", "GH"],
};

let df = new dfd.DataFrame(data);

dfd.toExcel(df, { filePath: "testOut.xlsx"});
Run Code Online (Sandbox Code Playgroud)