vue+elementui el-upload上传excel并前端解析到表格
安装: npm install xlsx --savevue组件引入:importXLSXfrom"xlsx";代码<el-uploadclass="upload":show-file-list="false"action="":multiple="false"...
·
安装: npm install xlsx --save
vue组件引入: import XLSX from "xlsx";
代码
<el-upload
class="upload"
:show-file-list="false"
action=""
:multiple="false"
accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
:on-change="importExcel"
:limit="1"
>
<el-button size="small" type="primary">上传</el-button>
</el-upload>
methods: {
// 导入表格
importExcel(param) {
// console.log(param);
let _this = this;
_this.file2Xce(param).then(item => {
if (item && item.length > 0) {
// xlsxJson就是解析出来的json数据,数据格式如下
// [{sheetName: sheet1, sheet: sheetData }]
if (item[0] && item[0].sheet && item[0].sheet.length) {
_this.tableData = item[0].sheet //把数据塞到表格预览
}
}
})
.catch(error => {
loading.close();
});
},
/**
* 解析文件
* @param {Object} file
*/
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,
sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
});
});
/* console.log("解析")
console.log(result) */
resolve(result);
};
reader.readAsBinaryString(file.raw);
});
}
}
更多推荐
已为社区贡献30条内容
所有评论(0)