【前端】浏览器端excel导入导出功能(ant-design-vue/element-plus, exceljs &FileReader & file-saver & web worker)

28 篇文章 0 订阅
3 篇文章 0 订阅

参考文档:

导出:

前端性能优化之 WebWorker 优化数据导出下载 Excel 操作
Web Worker

导入

<template>
	<a-upload
		accept=".csv,.xlsx"
		:show-upload-list="false"
		:before-upload="importFile"
	>
		<a-button>
			批量上传
		</a-button>
	</a-upload>
</template>

<script setup>
import { ref } from 'vue'
import Excel from 'exceljs'
// json格式的 excel 的数据
const tableRows = ref([])

const uploadExcelHander = (file, { header }) => {
  const excelData = []
  const buffer = new FileReader()
  buffer.onload = async function(e) {
    const result = new Uint8Array(e.target.result)
    const workbook = new Excel.Workbook()
    await workbook.xlsx.load(result)
    const worksheet = workbook.getWorksheet(1)
    worksheet.eachRow({ includeEmpty: true }, function (row, rowNumber) {
      if (rowNumber !== 1) {
        // 排除表头行
        let rowData = {}
        row.eachCell({ includeEmpty: true }, function (cell, colNumber) {
          if (colNumber < header.length) {
            const prop = header[colNumber]
            rowData[prop] = cell.value
          }
        })
        excelData.push(rowData)
      }
    })
    // callbackFn(excelData)
    tableRows.value = excelData
  }
  if (file) {
    buffer.readAsArrayBuffer(file)
  }
}

const importFile = file => {
	// 列的id
	const header = ['trading_date', 'account', 'symbol', 'vstrategy_id', 'trade_vol', 'trade_price', 'direction', 'open_close', 'daynight', 'trade_time', 'entrust_no']
	uploadExcelHander(file, { header })
}
</script>

遇到的问题

.csv 文件上传会报错:Uncaught (in promise) Error: Can’t find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html

.csv文件上传报错

exceljs 并不支持处理.csv 和 .xls 文件。
相关参考:
使用workbook.xlsx.load读取xls文件出错
Reading CSV file is giving error on browser console.
readFile error

解决方案
暂时还没找到能解决使用 exceljs 上传 .csv 文件并在浏览器解析成 json 的技术方案。
先读完这几篇文档再看看:一文了解文件上传全过程(1.8w字深度解析,进阶必备), 流式上传文件

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值