Loading

前端导入xlsx并表格显示【代码示例】

<template>
  <el-row justify="space-between">

    <input type="file" id="fileInput"/>

    <el-button type="success" @click="doSumbitFile">上传</el-button>
  </el-row>

  <!-- 此次错误原因:没搞清楚label和prop的数据格式,显示方式。 -->
  <!-- label应该是标签,prop是列表字典中的键(属性名) -->
  <el-table :data="state.tableData" border>
    <el-table-column
        align="center"
        :label="key"
        :prop="key"
        v-for="(value, key) in firstRow"
    >
    </el-table-column>
    <el-table-column label="操作" align="center">
      <template #default>
        <el-button type="success" size="small">
          <el-icon>
            <Edit/>
          </el-icon>
        </el-button>
        <el-button type="danger" size="small">
          <el-icon>
            <Delete/>
          </el-icon>
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {userInfoStore} from "@/stores/counter.js";
import * as XLSX from "xlsx";

const firstRow = ref({})
const upload = ref()
const store = userInfoStore()
const state = reactive({
  tableData: [],
  uploadUrl: 'http://localhost:8000/api/employ/upload/',
  form: {}
})


onMounted(
    function () {
      document.getElementById('fileInput').addEventListener('change', function () {
        const fileObj = this.files[0]
        // console.log(fileObj)

        // FileReader对象就是专门操作二进制数据的,主要用于将文件内容读入内存
        const fileReader = new FileReader()

        // readAsArrayBuffer,读取指定的 Blob或File内容
        fileReader.readAsArrayBuffer(fileObj)

        // 添加事件
        fileReader.onload = (event) => {

          // 是二进制文件
          const fileData = event.target.result

          // XLSX读取该二进制文件,获得工作簿
          const workbook = XLSX.read(fileData, {type: 'binary'})

          // 获取第一张表名称
          const sheetName = workbook.SheetNames[0]

          // 获取工作表
          const sheet = workbook.Sheets[sheetName];

          // 获取json
          const sheetData = XLSX.utils.sheet_to_json(sheet)

          state.tableData = sheetData
          console.log(sheetData)

          firstRow.value = sheetData[0]
          console.log(firstRow.value)

          for(let item in firstRow.value) {
            console.log(item)
          }

        }
      })
    }
)

function doSumbitFile() {

}

function uploadSuccessWrapper() {
  return function (res) {
    console.log(res)
  }
}
</script>

<style scoped>

</style>
posted @ 2024-10-13 16:46  一只大学生  阅读(15)  评论(0编辑  收藏  举报