返回
Express.js 中使用 node-xlsx 模块下载 Excel 表格
前端
2023-11-22 12:41:04
1. 安装 node-xlsx
npm install node-xlsx
2. 导入 node-xlsx
const xlsx = require('node-xlsx');
3. 读取本地文件并返回前端 Excel 流文件
const excelData = xlsx.parse('path/to/file.xlsx');
const workbook = excelData[0];
const sheet = workbook.sheets[0];
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=file.xlsx');
res.send(xlsx.build([sheet]));
4. 读取远程文件并返回前端 Excel 流文件
const request = require('request');
const excelData = xlsx.parse(request('https://example.com/file.xlsx'));
const workbook = excelData[0];
const sheet = workbook.sheets[0];
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=file.xlsx');
res.send(xlsx.build([sheet]));
5. 在 Express 路由中使用
const express = require('express');
const router = express.Router();
router.get('/download', (req, res) => {
const excelData = xlsx.parse('path/to/file.xlsx');
const workbook = excelData[0];
const sheet = workbook.sheets[0];
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=file.xlsx');
res.send(xlsx.build([sheet]));
});
module.exports = router;
希望本篇文章对您有所帮助。如果您有任何其他问题,请随时提出。