javascript - 如何从前端的后端下载excel文件?
问题描述
我想启动在我的后端生成的 excel 文件的浏览器下载,但我不知道如何传递这种响应。
app.get('/all', function (req, res) {
db.query(...) LIMIT 20000;")
.then(function (data) {
let result = []
data.forEach(element => {
result.push(element)
})
/* make the worksheet */
var ws = XLSX.utils.json_to_sheet(data);
/* add to workbook */
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "All");
XLSX.writeFile(wb, 'alltest1.xlsx'); //This saves the file in my server but I don't know how to send it as a response.
console.log('Ready');
res.send(result);
})
.catch(function (error) {
console.log("ERROR:", error)
})
})
我一直在尝试在前端创建 excel,但由于我认为数据量很大,chrome 内存不足。我也尝试过传递缓冲区,但我得到的文件似乎已损坏。
解决方案
设置文件的响应头Content-Disposition和Content-Type,告诉浏览器文件作为响应发送
res.setHeader('Content-Disposition',
"attachment; filename='alltest1'; filename*=UTF-8\'\'alltest1.xlsx");
res.setHeader('Content-Type', "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
并将文件内容作为响应发送
res.send(wb)
或者您也可以使用res.download。
res.download(filePath, fileName, (err) => { if (err) console.log(err); })
推荐阅读
- r - R 时间序列数据,按正比分组
- flutter - Flutter SingleChildScrollView 在 Stack 中不起作用
- reactjs - 如何将 TypeScript 与 React / Redux mergeProps 一起使用
- r - How to copy a value in new dataframe based on key links of another dataframe like ID, start and end value? (in R)
- php - Php PDO Mysql 选择值下拉列表
- html - WordPress。使整个 div 类可点击
- shopify - 如何使用 Shopify API 取消和补货?
- cmake - 如何在cmake中定义从使用ExternalProject_add构建的目标派生的变量?
- php - 在 mac catalina 上为 imap 功能加载正确的 php.ini 文件
- java - Spring WebFlux:Mono的单元测试订阅功能