HTLF

一步一个脚印,走出高度...

导航

vue 项目读取本地Excel方法

安装插件xlsx

npm install xlsx

在需要的页面引入插件

import * as xlsx from 'xlsx'

使用xlsx读取excel文件

  1. 点击上传Excel文件
<template>
<!-- 上传按钮 -->
  <el-upload action="#" :auto-upload="false" :on-change="handleFileSelect" accept=".xls,.xlsx">
    <el-button type="primary">上传excel</el-button>
  </el-upload>
<!-- 表格 -->
  <el-table
    :data="tableData"
    style="width: 100%"
    border="1"
    height="95%"
    stripe
    highlight-current-row
    current-row-key
    lazy="true"
    :cell-style="{ textAlign: 'center' }"
    :header-cell-style="{ textAlign: 'center' }"
    empty-text="暂无数据..."
  >
    <el-table-column
      v-for="item in columns"
      sortable
      :prop="item.prop"
      :label="item.label"
      :width="item.width"
      show-overflow-tooltip
    />
  </el-table>
</template>
  1. js获取数据方法
// 引入xlsx插件
import * as xlsx from 'xlsx'

// 表格数据
const tableData = ref([])
// 表格标题
const columns = ref([])

// 导入静态文件
// import fileExcel from '@/assets/data/data.xlsx'
onMounted(() => {})

const handleFileSelect = (event) => {
  const { name, raw: file } = event
  console.log('文件名称', name)

  const reader = new FileReader()
  // 处理文件内容
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result)
    // 获取表格中所欲 Sheet
    const workbook = xlsx.read(data, { type: 'array' })
    // 获取第一个sheet
    const worksheet = workbook.Sheets[workbook.SheetNames[0]]

    // 获取所有数据
    const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 })

    const _dataTable = []
    // 获取文件标题
    let headers = jsonData[0]
    // 设置表格标题
    const _columns = []
    headers.forEach((item) => {
      console.log(1, item.length)

      _columns.push({
        label: item,
        prop: item,
        width: item.length * 20
      })
    })

    // 设置对应标题数据
    jsonData.slice(1).forEach((row) => {
      const rowData = row.reduce((accumulator, item, index) => {
        let column = headers[index]
        accumulator[column] = item
        return accumulator
      }, {})
      // 更新标题

      // 赋值所有数据
      _dataTable.push(rowData)
    })

    columns.value = [..._columns]

    // 赋值表格数据
    tableData.value = [..._dataTable]
    console.log(1, tableData.value)
  }
  // 读取文件内容
  reader.readAsArrayBuffer(file)
}

-

posted on 2024-09-20 17:02  HTLF  阅读(2)  评论(0编辑  收藏  举报