vue读取本机的excel文件
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue

·
安装命令
npm install xlsx --save
在文件里直接引入
import { read, utils } from 'xlsx'
非elementUI使用
<template>
<input type="file" ref="upload" accept=".xls,.xlsx" class="outputlist_upload">
</template>
<script>
import { read, utils } from 'xlsx'
export default{
data() {
return {
outputs: []
}
},
mounted() {
this.$refs.upload.addEventListener('change', e => {//绑定监听表格导入事件
this.readExcel(e);
})
},
methods:{
readExcel(e) {
var that = this;
const files = e.target.files;
// 如果没有文件名
if(files.length<=0){
return false;
}else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
this.$Message.error('上传格式不正确,请上传xls或者xlsx格式');
return false;
}
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
// 切换为新的调用方式
const workbook = read(data, {
type: 'binary'
});
// 取第一张表
const wsname = workbook.SheetNames[0];
// 切换为新的调用方式 生成json表格内容
const ws = utils.sheet_to_json(workbook.Sheets[wsname]);
console.log(ws);
// 后续为自己对ws数据的处理
} catch (e) {
return false;
}
};
fileReader.readAsBinaryString(files[0]);
}
}
}
</script>
第二种,结合element UI 的upload
//dom结构
<el-upload
:drag="false"
action="#"
:auto-upload="true"
:multiple="false"
:show-file-list="false"
:before-upload="upload"
accept=".xlsx,.xls">
<el-button size="small" icon="el-icon-upload2" type="info">{{uploadTitle}}</el-button>
</el-upload>
//引入包相关方法
import { read, utils } from 'xlsx'
//触发的事件
upload(file,fileList){
console.log("file",file);
console.log("fileList",fileList);
let files = {0: file}
this.readExcel1(files);
return false; //false表示不需要上传~
}
// 表格导入
readExcel1(files) {
var that = this;
console.log(files);
// 此处判断不严谨,思路只是根据传入的参数校验数据的完整性,可根据自己需求修改
// 如果没有文件名
if(files.length <= 0){
return;
}
if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
this.$Message.error('上传格式不正确,请上传xls或者xlsx格式');
return;
}
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
const workbook = read(data, {
type: 'binary'
});
// 取第一张表
const wsname = workbook.SheetNames[0];
// 生成json表格内容
const ws = utils.sheet_to_json(workbook.Sheets[wsname]);
console.log(ws);
// 后续为自己对ws数据的处理
} catch (e) {
return false;
}
};
fileReader.readAsBinaryString(files[0]);
},




vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:28 天前 )
9e887079
[skip ci] 11 个月前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
更多推荐
所有评论(0)