我有 node.js 服务器,里面有转换器 excel4node,所以我接收对象并返回 Excel 文档(我相信它是二进制格式)
const port = '3001'
const stylers = require('./styleObjects.js')
const xl = require('excel4node')
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.post('/palmsnow/statements', function (req, res, next) {
const wb = new xl.Workbook();
const ws = wb.addWorksheet('Statements');
const { body: { exportRows, exportFields, excelName } } = req
const headerStyleObj = wb.createStyle(stylers.header)
const regularStyleObj = wb.createStyle(stylers.regular)
const regularHighlightedStyleObj = wb.createStyle(stylers.regular_highlighted)
exportFields.forEach((col, index) => {
ws.cell(1, index + 1).style(headerStyleObj);
ws.cell(1, index + 1).string(col.label);
ws.column(index + 1).setWidth(index ? 20 : 30)
})
exportRows.forEach((row, index) => {
const rowNumber = index + 2;
const styling = row.Description.startsWith('*') ? regularHighlightedStyleObj : regularStyleObj
Object.keys(row).forEach((key, keyIndex) => {
ws.cell(rowNumber, keyIndex + 1).string(row[key])
ws.cell(rowNumber, keyIndex + 1).style(styling)
if (keyIndex == 0) ws.cell(rowNumber, keyIndex + 1).style({
alignment: {
horizontal: 'left',
vertical: 'center'
}
})
})
})
wb.write(`${excelName}.xlsx`, res);
console.log(`File generated - ${new Date()}`)
})
app.listen(port, function () {
console.log(`App is currently running at ${port} port!`);
});
关键是 - wb.write( ${excelName}.xlsx
, res); . 所以它与邮递员配合得很好,我可以向这个端点发送请求并保存响应 - >通过邮递员保存到文件 - 它会下载我的 Excel 文件。
但是我怎样才能在浏览器中强制下载呢?在我的应用程序的客户端,我可以检索这个字符串,我可以在邮递员邮递员响应中看到 我有 fileSaver,我尝试了以下代码但没有成功(数据是我的响应 - 保存为邮递员) - 文件已损坏
import { saveAs } from 'file-saver';
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, "test.xlsx");