使用 node xlsx 获取 xlsx文件数据,以及导出excel数据
//获取数据
<el-upload class="upload-demo" action="###" accept='.xlsx' :http-request="customUpload"> <el-button size="small" type="primary">点击上传</el-button> </el-upload> import xlsx from 'xlsx' async readAsDataBinaryString (file) { const render = new FileReader() if (!render) { return '' } return new Promise((resolve, reject) => { render.onload = (res) => { // 在onload 可以获得上传文件 resolve(res.target.result) } render.readAsBinaryString(file) }) }, customUpload (content) { (async () => { if (!content.file) return const file = content.file const binaryString = await this.readAsDataBinaryString(file) const workbook = xlsx.read(binaryString, { type: 'binary', codepage: 936 }) const sheetNames = workbook.SheetNames const sheet = workbook.Sheets[sheetNames[0]] const data = xlsx.utils.sheet_to_json(sheet) const filterData = data.slice(1, data.length) if (filterData.length === 0) return this.$message.error('文件为空!') _.each(filterData, async item => { const params = { menuPath: 'CASH_VALUE-CASH_VALUE', compareVersion: 0, data: item } await addVersion(params) await sleep(600) }) this.$message.success('导入成功!') })() }
// 导出
toHump (str) {
// 下划线转驼峰命名
return str.replace(/_(\w)/g, function (all, letter) {
return letter.toUpperCase()
})
},
handleDownload (row) {
const printData = [
{
comboCode: '方案编码',
riskCode: '险种编码',
dutyCode: '缴费责任编码',
policyYear: '保单年度',
applicantAge: '投保人年龄',
applicantGender: '投保人性别',
age: '被保人年龄',
gender: '被保人性别',
collectPeriod: '交费期间',
insurePeriod: '保险期间',
modx: '缴别',
unitAmount: '单位保额',
unitPremium: '单位保费',
getYear: '年金起领时间',
getPeriod: '年金领取期限',
cashvalueRate: '现价费率'
}
]
const keys = Object.keys(row)
const pushkey = ['comboCode', 'riskCode', 'dutyCode', 'policyYear', 'applicantAge', 'applicantGender', 'age', 'gender', 'collectPeriod', 'collectPeriod', 'insurePeriod', 'modx', 'unitAmount', 'unitPremium', 'getYear', 'getPeriod', 'cashvalueRate']
const pushData = {}
_.each(keys, item => {
const k = this.toHump(item)
if (pushkey.indexOf(k) !== -1) {
pushData[k] = row[item]
}
})
printData.push(pushData)
// 创建一个新sheet
const newSheet = xlsx.utils.json_to_sheet(printData)
// 设置每列的列宽(可选),10代表10个字符,注意中文占2个字符
newSheet['!cols'] = [
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 },
{ wch: 15 }
]
// 新建book
const newBook = xlsx.utils.book_new()
// 将 sheet 添加到 book 中
xlsx.utils.book_append_sheet(newBook, newSheet, '现价表')
// 导出excel文件
xlsx.writeFile(newBook, '现价表.xlsx')
}