Vue中使用xlsx库解析Excel

<template>
 <div>
  <el-upload
   ref="upload"
   class="upload-demo"
   action="#"
   accept="xlsx,xls"
   multiple
   :limit="1"
   :auto-upload="false"
   :withCredentials="false"
   :on-change="loadFile"
  >
   <el-button slot="trigger" size="mini" type="success" plain round>选择文件</el-button>
   <br />
   <div slot="tip" class="el-upload__tip">【注意】只能上传xls/xlsx文件</div>
  </el-upload>
 </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
 name: 'GetExcelContent',
 data() {
  return {
   tableData: []
  }
 },
 methods: {
  handle_download(row) {
   return this.$message.success(`下载版本号为 ${row.version} 的文件!`)
  },
  loadFile(file, fileList) {
   let upload_file = fileList[0].raw
   const reader = new FileReader()
   reader.readAsBinaryString(upload_file)
   reader.onload = (ev) => {
    try {
     const f = ev.target.result
     const workbook = XLSX.read(f, { type: 'binary', codepage: 936 }) // codepage 解决中文乱码问题 
     const wsname = workbook.SheetNames[0]
     //  console.log(wsname) // 工作簿名称
     const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname], { header: 1, defval: '#' })
     //至此,将拿到excel工作簿中的数据,下面就可以自己操作了
     //........
     let excelData = ws
let key_list = excelData[0] console.log(
'原始数据:', excelData) let object_data = {} this.excelData.forEach((item, key) => { if (key != 0) { item.forEach((element, index) => { object_data[key_list[index]] = item[index] }) this.tableData.push(object_data) object_data = {} } }) console.log('格式化后的数据:', this.tableData) } catch (e) { console.log(e) return false } } }, }, } </script> <style lang="scss" scoped></style>

 

posted @ 2024-09-27 10:27  yw3692582  阅读(50)  评论(0编辑  收藏  举报