本文最后更新于 340 天前,其中的信息可能已经有所发展或是发生改变。
官方文档
xlsx.js
官方文档
安装 xlsx.js
# yarn
yarn add xlsx
# npm
npm install --save xlsx
演示数据
// 表头
const baseColumns = [
{
title: 'Name',
key: 'name',
},
{
title: 'Age',
key: 'age',
},
{
title: 'Address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
},
{
title: 'Action',
key: 'actions',
},
]
// 数据
const baseData = [
{
key: 0,
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: 1,
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['wow'],
},
{
key: 2,
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
tags: ['cool', 'teacher'],
},
]
使用 xlsx.js
导出
import { utils, writeFileXLSX } from 'xlsx'
const sheetData = utils.json_to_sheet(baseData) // 将所有数据转换为表格数据类型
const workBook = utils.book_new() // 创建工作簿
const filename = '导出示例.xlsx'
writeFileXLSX(workBook, filename) // 输出表格
到目前为止可以直接输出表格了,但是,不能友好的设置表头。所以,我们再来改进一下
import { utils, writeFileXLSX } from 'xlsx'
interface ExportExcelHeader {
title: string | number
key: string | number
}
const setupExportHeader = (columns: ExportExcelHeader[]) => {
const header = columns.reduce((pre, curr) => {
pre[curr.key] = curr.title
return pre
}, {} as ExportExcelHeader)
return header
}
const exportHeader = setupExportHeader(baseColumns)
const sheetData = utils.json_to_sheet(baseData) // 将所有数据转换为表格数据类型
const workBook = utils.book_new() // 创建工作簿
const filename = '导出示例.xlsx'
utils.book_append_sheet(workBook, sheetData, 'Data') // `Data` 为工作簿标题,可以自定义
const range = utils.decode_range(sheetData['!ref'] as string) // 获取所有单元格
/**
*
* 替换表头
*
* 网上查找相关方法,并没有实现需求,所以采用这样的方法
*
* 如果有好的实现方法可以联系本人,<https://github.com/XiaoDaiGua-Ray>
*/
for (let c = range.s.c; c <= range.e.c; c++) {
const header = utils.encode_col(c) + '1'
sheetData[header].v = exportHeader[sheetData[header].v]
}
writeFileXLSX(workBook, filename) // 输出表格
这样就可以实现自定义表头导出表格了
使用 xlsx.js
导入
import { read, utils } from 'xlsx'
const f = await fetch('https://sheetjs.com/pres.numbers')
const ab = await f.arrayBuffer()
/* parse workbook */
const wb = read(ab)
/* update data */
const html = utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]])
这里是搬用官方文档的示例,就不做过多的赘述,因为直接调用
read
方法即可