nodejs+jsxlsx使用文件流方式下载excel
简介
本文介绍用 Node.js 中的依赖库来处理 Excel 文件,主要利用js-xlsx库来处理 Excel 文件。
1.安装依赖
npm install xlsx
2.导入xlsx库
const Excel = require ('xlsx')
3.查询所需导出的数据
栗子:
const users = await this._User.findAll({
attributes:['firstName', 'lastName', 'email']
})
4.将数据转成Excel表横坐标展示的
假如数据的类型是json,如下所示:
let ws = Excel.utils.json_to_sheet(users)//这里的users就是数据
数据类型是数组的话,如下所示:
let ws = Excel.utils.aoa_to_sheet(users)
我这里是第一种✌️
5.创建表格
let wb = Excel.utils.book_new()
6.数据装载到工作薄上
Excel.utils.book_append_sheet(wb, ws, 'users用户信息')//最后那个是工作薄表的命名
7.最后就是采用文件流的方式相应的设置
let buf = Excel.write(wb, {
type: 'buffer',
bookType: 'xlsx'
})
8.设置文件名之类的
let filename = 'users.xlsx'
ctx.set('Content-disposition', 'attachment; filename=' + filename);
ctx.type = "xlsx"
ctx.body = buf
return buf
9.好啦可以试试 应该就成功啦
9.想要中文表头
下面直接粘贴源码吧!
const fields = [ 'firstName', 'lastName', 'email', 'describe.introduce', 'describe.age']
const titles = {
firstName: '姓',
lastName: '名',
email: '邮件',
'describe.introduce': '介绍',
'describe.age': '年龄'
}
const ws = Excel.utils.json_to_sheet(
users,
{
header: fields
}
)
const range = Excel.utils.decode_range(ws['!ref'])
for(let c = range.s.c; c <= range.e.c; c++) {
const header = Excel.utils.encode_col(c) + '1'
ws[header].v = titles[ ws[header].v ]
}