1、安装 xlsx (这里建议指定版本)
npm i xlsx@0.17.5 -S
2、代码示例
<div class="importBox">
<input v-show="false" ref="uploadButton" type="file" accept=".xlsx,.xls" @change="handleChange" />
<div>
<span style="font-size: 16px;">选择文件:</span>
<a-button type="primary" @click="uploadHandler">导入excel</a-button>
</div>
</div>
<a-button class="importButton" type="primary" @click="confirmImport">确认导入</a-button>
预览 excel 容器
<div class="table_box" v-html="tableContext"></div>
export default {
data() {
return {
tableContext: "暂无数据",
}
},
methods: {
uploadHandler() {
this.$refs.uploadButton.value = null;
// 手动触发点击事件
this.$refs.uploadButton.click();
},
// 文件上传事件
handleChange(e) {
let _this = this;
let file = e.target.files[0];
// 创建一个FileReader实例
const reader = new FileReader();
// 设置FileReader的onload事件处理程序,当读取操作完成时会调用
reader.onload = function (event) {
// 通过event.target.result获取转换后的ArrayBuffer结果
const arrayBuffer = event.target.result;
// 处理arrayBuffer...
console.log(arrayBuffer);
const data = new Uint8Array(arrayBuffer);
const workbook = XLSX.read(data, {
type: "array",
});
console.log("读取的数据", workbook);
// 删除掉没有数据的sheet
Object.values(workbook.Sheets).forEach((sheet, index) => {
if (Object.keys(sheet).indexOf("!ref") === -1) {
delete workbook.Sheets[workbook.SheetNames[index]];
}
});
_this.tableToHtml(workbook);
};
// 使用FileReader的readAsArrayBuffer方法来读取文件内容
reader.readAsArrayBuffer(file);
},
// 预览excel文件
tableToHtml(workbook) {
const sheetList = workbook.SheetNames.filter(
(v) => v.indexOf("数据源") === -1
);
sheetList.forEach((sheet) => {
const worksheet = workbook.Sheets[sheet];
console.log("数据源:", worksheet);
if (worksheet) {
this.tableContext = XLSX.utils.sheet_to_html(worksheet);
}
});
console.log('读取结果:', this.tableContext)
},
confirmImport() {
console.log(this.$refs.uploadButton.files)
const file = this.$refs.uploadButton.files[0];
const formData = new FormData();
formData.append('file', file);
// 文件上传接口
importGovernmentStaff(formData).then(res=>{
if(res.code === 0){
this.$message.success('导入成功')
this.reloadTable()
}else{
this.$message.error(res.msg)
}
})
},
}
}
<style scoped>
.table_box {
width: 100%;
max-height: 500px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-bottom: none;
overflow: auto;
}
.table_box /deep/ table {
width: 100%;
text-align: center;
}
.table_box /deep/ td {
padding: 5px 20px;
border-right: 1px solid #cccccc;
border-bottom: 1px solid #cccccc;
}
.importButton {
margin-left: 50%;
transform: translateX(-50%);
margin-top: 20px;
}
</style>