在使用vue的xlsx解析文件時,由于我的excel文件沒有標題行,第一行就是內(nèi)容了,在使用默認解析方法時,將第一行的內(nèi)容解析成了列名,查看文檔后,返現(xiàn)在使用XLSX.utils.sheet_to_json方法時,要增加參數(shù){header:1}來取消標題列.
xlsx官方文檔:https://www.npmjs.com/package/xlsx
下面是我的關于文件解析的代碼:
<el-form-item label="excel文件" label-width="110px">
<el-upload ref="upload" action=""
multiple
:on-change="changeFileList"
:on-remove="changeFileList"
:auto-upload="false"
:http-request="httpFile"
:file-list="fileList"
accept=".xlsx">
<el-button size="small" type="primary" >點擊上傳</el-button>
<div slot="tip" class="el-upload__tip">
格式說明:
</div>
</el-upload>
</el-form-item>
data() {
return {
fileList:[],
fullscreenLoading:false,
fileList:[],
updateFileList:[],
xlsxDate:[],
}
}
method(){
//更改文件文件的方法,在文件上傳按鈕中使用:on-change方法屬性綁定,file參數(shù)是更改的文件,fileList是已選擇附件的集合.
changeFileList(file, fileList){
this.fullscreenLoading = true;
this.xlsxDate=[];
this.updateFileList = fileList;
//重新遍歷所有的文件進行解析
var j;
var len;
for(j = 0,len=this.updateFileList.length; j < len; j++) {
this.file2Xce(this.updateFileList[j]).then(tabJson => {
if (tabJson && tabJson.length > 0) {
this.xlsxJson = tabJson;
var i;
var leng;
for(i = 0,leng=this.xlsxJson[0].sheet.length; i < leng; i++) {
this.xlsxDate.push(this.xlsxJson[0].sheet[i]);
}
}
})
};
console.log(this.updateFileList);
setTimeout(() => {
this.fullscreenLoading = false;
}, 2000);
},
//解析xlsx文件
file2Xce(file) {
return new Promise(function(resolve, reject) {
const reader = new FileReader()
reader.onload = function(e) {
const data = e.target.result
this.wb = XLSX.read(data, {
type: 'binary'
})
const result = []
this.wb.SheetNames.forEach((sheetName) => {
result.push({
sheetName: sheetName,
//添加{header:1},表示第一行不為標題,直接按內(nèi)容解析為json.
sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName],{header:1})
})
})
resolve(result)
}
reader.readAsBinaryString(file.raw)
})
}
}
如果是有多行標題的情況,可以在解析前,刪除多余的標題行.