通过 xlsx 解析上传excel的数据

一、前言

在前端开发中,特别是在后台管理系统中,导入数据(上传excel)到后端是是否常见的功能;而一般的实现方式都是通过接口将excel上传到后端,再有后端进行数据解析并做后续操作。

今天,来记录一下前端通过 xlsx 直接解析得到数据。

二、安装依赖

bash 复制代码
npm i XLSX --save

三、上传文件解析数据

javascript 复制代码
<template>
  <div>
    <!-- 不自动上传,不显示上传的列表,只能上传一个 -->
    <el-upload
      ref="xlsxUploadRef"
      action=""
      :show-file-list="false"
      :auto-upload="false"
      :on-change="onChange"
      accept=".xls,.xlsx"
      :limit="1"
    >
      <!-- 自定义按钮 -->
      <slot></slot>
    </el-upload>

  </div>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
  name: 'ResolveExcel',
  props: {
    fileType: { // 数据表类型
      type: Number,
      default: 1
    }
  },
  methods: {
    readFile(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        reader.readAsBinaryString(file)
        reader.onload = (ev) => {
          resolve(ev.target.result)
        }
      })
    },
    async onChange(file) {
      // 格式检验
      if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        this.$modal.msgError('上传格式不正确,请上传xls或者xlsx格式')
        return false
      }

      const dataBinary = await this.readFile(file.raw)
      const workBook = XLSX.read(dataBinary, {
        type: 'binary',
        cellDates: true
      })
      const workSheet = workBook.Sheets[workBook.SheetNames[0]]
      const data = XLSX.utils.sheet_to_json(workSheet)
      console.log('XLSX数据', data) // excel 中没事数据是,data = []

      // 格式化数据, 并将数据回传;formatData 方法需要根据excel内的数据进行开发;此处并没有实现,实现开发中,该方法可能在父组件实现(多个地方使用,表格内容不一致,无法共用)
      const resultArr = this.formatData(data)
      this.$emit('getXlsxData', resultArr);

      this.$nextTick(() => { // 数据拿到后,清空上传列表,才能继续上传解析
        this.$refs.xlsxUploadRef.clearFiles();
      })
    }
  }
}
</script>

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!

相关推荐
QQ3596773452 小时前
ArcGIS Pro实现基于 Excel 表格批量创建标准地理数据库(GDB)——高效数据库建库解决方案
数据库·arcgis·excel
星空的资源小屋2 天前
Digital Clock 4,一款免费的个性化桌面数字时钟
stm32·单片机·嵌入式硬件·电脑·excel
揭老师高效办公2 天前
在Excel和WPS表格中批量删除数据区域的批注
excel·wps表格
我是zxb2 天前
EasyExcel:快速读写Excel的工具类
数据库·oracle·excel
辣香牛肉面2 天前
[Windows] 搜索文本2.6.2(从word、wps、excel、pdf和txt文件中查找文本的工具)
word·excel·wps·搜索文本
ljf88382 天前
Java导出复杂excel,自定义excel导出
java·开发语言·excel
tebukaopu1482 天前
json文件转excel
json·excel
shizidushu2 天前
How to work with merged cells in Excel with `openpyxl` in Python?
python·microsoft·excel·openpyxl
Eiceblue3 天前
使用 C# 设置 Excel 单元格格式
开发语言·后端·c#·.net·excel
acaad3 天前
Apache Poi 实现导出excel表格 合并区域边框未完全显示的问题
spring·apache·excel