安装
pnpm add -S XLSX
方法封装
import * as XLSX from 'xlsx'
export const ExportXlsx = (configuration) => {
const { data, head, name, label, widthArr } = configuration
const list = data.map((item) => {
const obj = {}
for (const k in item) {
if (head[k]) {
obj[head[k]] = item[k]
}
}
return obj
})
const xLSXData = XLSX.utils.json_to_sheet(list)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, xLSXData, label)
xLSXData['!cols'] = []
widthArr.forEach((item) => {
xLSXData['!cols'].push({ wpx: item })
})
XLSX.writeFile(wb, `${name}.xlsx`)
}
export const ImportXlsx = (e) => {
const file = e.target.files[0]
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = (e) => {
const data = e.target.result
const workbook = XLSX.read(data, { type: 'binary', cellDates: true })
const wsname = workbook.SheetNames[0]
const outdata = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
console.log(outdata)
}
}
参数说明
变量 | 类型 | 释意 |
---|
data | 数组 | 导出的数据 |
head | 对象 | 导出的数据对应的表头 |
name | 字符串 | 导出的文件名 |
label | 字符串 | 导出的表单名 |
widthArr | 数组 | 导出的表单列宽 |