js批量导入获取xlsx文件数据

发布时间:2024年01月04日

1.安装xlsx

npm install xlsx

2.组件封装

通过input标签是先上传并读取文件内容

<template>
  <label class="custom-file-upload">
    <i class="el-icon-folder-add" />
    <div>
      {{ name }}
    </div>
    <input
      id="fileInput"
      type="file"
      :value="files"
      accept=".xlsx"
      @change="handleFileUpload"
    >
  </label>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
  props: {
    name: {
      type: String,
      default: '导入'
    }
  },
  data() {
    return {
      files: '',
      data: []
    }
  },
  methods: {
    handleFileUpload(event) {
      const file = event.target.files[0]
      const formData = new FormData()
      formData.append('file', file)
      const reader = new FileReader()
      reader.onload = (e) => {
        const binaryString = e.target.result
        const workbook = XLSX.read(binaryString, { type: 'binary' })
        const worksheet = workbook.Sheets[workbook.SheetNames[0]]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        this.$emit('upload', jsonData)
      }
      reader.readAsBinaryString(file)
    }
  }
}
</script>
  <style lang="scss" scoped>
  /* 自定义file类型的input */
  #fileInput {
    display: none;
  }

  .custom-file-upload {
    height: 29px;
    background-color: #ffffff;
    border: 1px solid #dcdcdc;
    border-radius: 3px;
    cursor: pointer;
    color: #606266;
    font-size: 12px;
    padding: 0 14px;
    font-weight: 400;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 10px 0 0;
    div{
        margin-left: 5px;
    }
  }
  .custom-file-upload:hover {
      background-color: #f5f5f5;
    }
  </style>

文章来源:https://blog.csdn.net/q12as/article/details/135382975
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。