1:先安装第三方插件
npm install xlsx
2:在文件中引入
import XLSX from 'xlsx'
将读取表格文件的js封装成一个函数,并用Promise返回读取表格结果
function uploadExcel (file) {
return new Promise(function (resolve,reject) {
let reader = new FileReader()
reader.readAsBinaryString(file)
reader.onload = function(e) {
//workbook存放excel的所有基本信息
let workbook = XLSX.read(e.target.result, {type: 'binary'})
//定义sheetList中存放excel表格的sheet表,就是最下方的tab
let sheetList = workbook.SheetNames
//存放字符串数组格式的表格数据
let formulaeResult = []
//存放json数组格式的表格数据
let jsonResult = []
//读取第一个sheet
jsonResult = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
formulaeResult = XLSX.utils.sheet_to_formulae(workbook.Sheets[workbook.SheetNames[0]])
let header = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1})
//读取所有的sheet
// sheetList.forEach(function(y) {
// let json = XLSX.utils.sheet_to_json(workbook.Sheets[y])
// let formulae = XLSX.utils.sheet_to_formulae(workbook.Sheets[y])
// if(json.length >0){
// jsonResult.push(...json)
// formulaeResult.push(...formulae)
// }
// });
let result = {header:header[0],
list:jsonResult}
resolve(result)
}
})
}