node读写xlsx

xlsx: Microsoft Office EXCEL 2007/2010/2013/2016/2019文档的扩展名。xlsx是从Office2007开始使用的,是用新的基于XML的压缩文件格式取代了其目前专有的默认文件格式,在传统的文件名扩展名后面添加了字母x(即:docx取代doc、.xlsx取代xls等等),使其占用空间更小。

npm里有包node-xlsx可以处理xlsx。

生成xlsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import fs from 'fs'
import { build } from 'node-xlsx'

const data = []

// title
data.push(['id', 'name', 'age'])

// content 随机生成的
for (let index = 0; index < 10; index++) {
let id = index + 1
let name = `我是${id}先生`
let age = Math.floor(id * Math.random() + 10)
data.push([id, name, age])
}

// sheet name: people
let buffer = build([{ name: `people`, data: data }])

// file name: people.xlsx
fs.writeFileSync('people.xlsx', buffer, { 'flag': 'w' })

运行上面的js,将会得到一个people.xlsx,里面有刚才生成的数据。

解析xlsx

1
2
3
import { parse } from 'node-xlsx'

const workSheetsFromFile = parse(`${__dirname}/people.xlsx`)

那么这个workSheetsFromFile的结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
[ { name: 'people',
data:
[ [Array],
[Array],
[Array],
[Array],
[Array],
[Array],
[Array],
[Array],
[Array],
[Array],
[Array] ] } ]

xlsx由多个workSheet构成,第一个workSheet就是我们刚才生成的people,data就是刚才临时的数据,遍历即可获取。

其他

node-xlsx包提供了简单的读写xlsx的能力,相对于xlsx本身拥有的功能,node-xlsx功能不足,可以参考另外一个xlsx包,xlsx包提供了更加强大的功能。