1歌殃、導(dǎo)入模塊
import Excel from 'exceljs' // excel解析模塊
import FileSaver from 'file-saver'
2乔妈、解析excel文件,獲取數(shù)據(jù)
let workbook = new Excel.Workbook() // 創(chuàng)建excel文件對(duì)象
let reader = new FileReader()
reader.readAsArrayBuffer(file) // <input type="file" />
reader.onloadend = function (event) {
let arrayBuffer = reader.result
workbook.xlsx.load(arrayBuffer).then(function (workbook) {
let sheet = workbook.getWorksheet(1) // 獲取第一個(gè)sheet
if (sheet) {
workbook.worksheets[0].eachRow(function (row, rowNumber) {
if (rowNumber > 1) {
let customreName = row.values[1]
let address = row.values[2]
customreName = customreName.trim().replace(/\n/g, '')
address = address.trim().replace(/\n/g, '')
locations.push({
customreName: customreName,
address: address
}) // 得到的數(shù)據(jù)
}
})
}
})
}
3氓皱、將數(shù)據(jù)寫入excel路召,得到excel文件
const workbook = new Excel.Workbook(); // 創(chuàng)建文件
const sheet = workbook.addWorksheet("My Sheet"); // 創(chuàng)建表
sheet.columns = [ // 設(shè)置表頭
{ header: '客戶名稱', key: 'customreName', width: 40, style: { font: { size: 14 } } }, // 表頭,對(duì)應(yīng)數(shù)據(jù)屬性為`key`值
{ header: '客戶地址', key: 'address', width: 40, style: { font: { size: 14 } } },
{ header: '聯(lián)系人姓名', key: 'contractName', width: 20, style: { font: { size: 14 } } },
{ header: '聯(lián)系人電話', key: 'contractTelPhone', width: 20, style: { font: { size: 14 } } }
];
sheet.addRows(records) // 將對(duì)應(yīng)的數(shù)據(jù)添加進(jìn)workbook對(duì)象
workbook.xlsx.writeBuffer().then((result) => {
const blob = new Blob([result], { type: "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
FileSaver.saveAs(blob, 'xxxx.xlsx')
})
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者