express - 在后端使用 excel4node 在前端下载 excel 文件
问题描述
我知道以前有人问过这个问题,但我无法让它工作。后端正在使用发送文件,wb.write('filename.xlsx', res)
但在前端,我只得到一个对象响应。如何让浏览器改为下载 .xlsx 文件?
// express backend
const x1 = require('excel4node');
router.get('/excel', async (req, res) => {
const wb = new x1.Workbook();
// do some stuff
wb.write('excel.xlsx', res);
});
// frontend
axis(config).then((res) => {
// What do I do here? res is an object. How do I handle this response so that the browser is downloading the file instead?
}).catch(...);
解决方案
前端的答案,
你可以编写如下的axios代码:
axios.get('URL TO GET FILE BLOB', {
responseType: 'blob'
}).then(response => {
let headerLine = response.headers['content-disposition'];
let startFileNameIndex = headerLine.indexOf('"') + 1
let endFileNameIndex = headerLine.lastIndexOf('"')
let filename = headerLine.substring(startFileNameIndex, endFileNameIndex)
const url = window.URL.createObjectURL(new Blob([response.data],
{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
link.remove();
}).catch(error => {
console.log(error)
})
后端:
您需要确保正确配置了 CORS,供您参考,请检查以下代码。
const express = require('express');
const xl = require('excel4node');
const cors = require('cors') //use this
const app = express();
app.use(cors({exposedHeaders: '*'})) //and this
const PORT = process.env.PORT || 3001;
app.get('/', (req, res) => {
var wb = new xl.Workbook();
// Add Worksheets to the workbook
var ws = wb.addWorksheet('Sheet 1');
var ws2 = wb.addWorksheet('Sheet 2');
// Create a reusable style
var style = wb.createStyle({
font: {
color: '#FF0800',
size: 12,
},
numberFormat: '$#,##0.00; ($#,##0.00); -',
});
// Set value of cell A1 to 100 as a number type styled with
ws.cell(1, 1)
.number(100)
.style(style);
// Set value of cell B1 to 200 as a number type styled with
paramaters of style
ws.cell(1, 2)
.number(200)
.style(style);
// Set value of cell C1 to a formula styled with paramaters of style
ws.cell(1, 3)
.formula('A1 + B1')
.style(style);
// Set value of cell A2 to 'string' styled with paramaters of style
ws.cell(2, 1)
.string('string')
.style(style);
// Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
ws.cell(3, 1)
.bool(true)
.style(style)
.style({font: {size: 14}});
wb.write('Excel.xlsx', res);
});
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
在前端,我们可以从内容配置头中提取文件名和扩展名。这是我们设置的同名
wb.write('Excel.xlsx', res);
推荐阅读
- python - “模型”对象没有属性“_name”
- java - addListenerForSingleValueEvent 被多次触发
- azure - Azure 函数 v 2.0 和 azure 服务总线触发器
- mysql - MySQL 1136 插入具有自动递增和默认字段的值时出错
- ruby - 构建 jekyll 时无法识别 _config.yml
- c++ - 根据 boost 1.68 的文档,不推荐使用旧的 io_context::post 。推荐使用 boost::asio::post()。谁能给我一个例子?
- javascript - 当我使用 typescript@3.0.1 时,字符串 [] 上不存在包含函数
- r - 在 R 中复制列
- c# - 使用 Visual Studio 2017 在 IIS 中发布或部署 Web api 项目
- java - Java 在对象的 2 个字符串变量数组之间没有区别(更新)