写vue excel导入
时间: 2023-10-31 14:48:47 浏览: 67
您好!关于导入Excel表格,可以使用第三方库xlsx和file-saver,代码如下:
1.安装依赖:
npm install xlsx file-saver --save
2.在.vue文件中引入依赖:
import XLSX from 'xlsx';
import FileSaver from 'file-saver';
3.定义一个方法用于Excel导入:
methods: {
handleImportFile(e) {
const files = e.target.files;
if (files.length) {
const fileReader = new FileReader();
fileReader.onload = e => {
try {
const data = e.target.result;
const workbook = XLSX.read(data, { type: 'binary' });
const sheetNames = workbook.SheetNames;
const worksheet = workbook.Sheets[sheetNames[0]];
const headers = {};
const data = [];
for (const key in worksheet) {
if (key[0] === '!') continue;
let col = key.substring(0, 1);
let row = parseInt(key.substring(1));
const value = worksheet[key].v;
if (row === 1) {
headers[col] = value;
continue;
}
if (!data[row]) data[row] = {};
data[row][headers[col]] = value;
}
// 删除第一个空对象
data.shift();
console.log(data);
} catch (e) {
console.log('导入失败', e);
}
};
fileReader.readAsBinaryString(files[0]);
}
}
}
4.在模板中添加一个input元素用于选择文件:
<template>
<div>
<input type="file" @change="handleImportFile" accept=".xlsx, .xls" />
</div>
</template>
希望以上代码能够帮到您,如有问题可以随时联系我哦!
阅读全文