vue3中读取本地excel文件内容
背景
做后台项目时避免不了excel文件上传,有的还要求对文件内容做校验,或者把文件内容转成数据上传保存.
操作
1.引入xlsx插件,最好安装指定版本,否则会报错
npm i xlsx@0.16.0 -save
2.页面引入
import XLSX from 'xlsx'
3.页面触发
<el-upload class="upload-demo" ref="upload" accept=".xls,.xlsx" action="" :on-change="uploadExcel"
:show-file-list="false" :auto-upload="false">
<el-button slot="trigger" size="large">导入excel</el-button>
</el-upload>
4.使用处理数据
import { ref } from 'vue'
import XLSX from 'xlsx'
const menuData: any = ref([])
const tableData: any = ref([])
const uploadExcel = (file: any, fileList: any) => {
let files = { 0: file.raw }
const fileReader = new FileReader()
fileReader.onload = (e: any) => {
try {
const workbook = XLSX.read(e.target.result, {
type: 'binary'
})
const wsname = workbook.SheetNames[0] // 取第一张表
const ws: any = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
const data: any = []
ws.map((item: any) => {
let obj: any = {
arr:[]
}
Object.values(item).map((child: any, index: number) => {
obj.arr.push('name' + index)
obj[`name${index}`] = child
})
data.push(obj)
})
tableData.value = data
menuData.value = Object.keys(ws[0])
} catch (err) {
console.log(err)
}
}
fileReader.readAsBinaryString(files[0])
}
excel文件如下:
读取后,处理数据展示如
具体代码地址:https://gitee.com/yuexiayunsheng/vue3learn/blob/master/src/views/GetExcelContent.vue
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
2022-03-03 element ui cascader级联选择器 动态加载以及回显