Vue 中导入 Excel 文件

<template>
  <el-upload
    action=""
    :auto-upload="false"
    :on-change="handleFileChange"
    accept=".xlsx, .xls"
  >
    <el-button type="primary">点击上传Excel文件</el-button>
  </el-upload>

  <el-table :data="tableData" style="width: 100%" v-if="tableData.length">
    <el-table-column
      v-for="(header, index) in tableHeaders"
      :key="index"
      :prop="header"
      :label="header"
    />
  </el-table>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  data() {
    return {
      tableData: [],
      tableHeaders: []
    }
  },
  methods: {
    handleFileChange(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        
        if (jsonData.length > 0) {
          this.tableHeaders = jsonData[0]
          this.tableData = jsonData.slice(1).map(row => {
            const obj = {}
            this.tableHeaders.forEach((header, index) => {
              obj[header] = row[index] || ''
            })
            return obj
          })
        }
      }
      reader.readAsArrayBuffer(file.raw)
    }
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值