vue3+ts前端导入xls

371 阅读1分钟

前言

前段时间遇到了一个需求导入xls,我直接就去npm上找了一个包xlsx,这个包的api我先在npm上看了一下感觉功能很全,ok准备工作就绪直接开工。先理一下需求,功能对xls的导入。

xls导入

通过查看xlsx的api发现他是需要先读取一个file文件流,然后通过XLSX中的read的api来读取导入的xls中的数据,第一步我们可以先对用户上传的xls文件格式进行确定,可以通过书写json的形式来确定。我们先来定义一下json的类型。

  type DataDictionaryItem = {
    key: string
    title: string
    value: string
  }

定义一个json

    const DataDictionaryArr: DataDictionaryItem[] = [
      {
        key: "A",
        title: "序号",
        value: "id"
      },
      {
        key: "B",
        title: "姓名",
        value: "name"
      },
      {
        key: "C",
        title: "性别",
        value: "sex"
      }
    ]

这样我们就已经规范了用户上传的格式要求他是一个这种格式

image.png

第二步我们就可以写我们的导入hook了

    //导入
const getExcel = async (file:File,dataDictionary:DataDictionaryItem[]) => {
  const data = await file.arrayBuffer();
  const wb = XLSX.read(data)
  const newWbData:wbData<DataDictionaryItem[]>[] = []
  let newData:wbData<DataDictionaryItem[]> = {}
  dataDictionary.forEach(item => {
    newData[item.value] = ''
  })
  let index = 1
  while (wb.Sheets[wb.SheetNames[0]][`${dataDictionary[0].key}${index+1}`]){
    newWbData.push({...newData})
    dataDictionary.forEach(item => {
      wb.Sheets[wb.SheetNames[0]][`${item.key}${index+1}`] && (newWbData[index-1][item.value] = 
        wb.Sheets[wb.SheetNames[0]][`${item.key}${index+1}`].v)
    })
    index++
  }
  return newWbData
}

可以简单的写一个上传文件组件来调用一下咱们写的hook

//html部分
 <el-upload
      class="upload-demo"
      action="#"
      :before-upload="beforeUploadXLS"
      :on-success="onSuccess"
      multiple
    >
      <el-button size="small" type="primary">上传xls</el-button>
    </el-upload>
 //ts部分
   
  const beforeUploadXLS = async (rawFile: UploadRawFile) => {
    const DataDictionaryArr: DataDictionaryItem[] = [
    {
        key: "A",
        title: "序号",
        value: "id"
      },
      {
        key: "B",
        title: "姓名",
        value: "name"
      },
      {
        key: "C",
        title: "性别",
        value: "sex"
      },
    ]
    const data = await getExcel(rawFile, DataDictionaryArr)
    console.log(data)
      return false
  }
  //console打印出来的值 [{id:1,name:'wzc',sex:'男'}]

我们就完成对xls的导出了,遇到同样问题的小伙伴快试试吧