参考文档:
导出:
前端性能优化之 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
exceljs 并不支持处理.csv 和 .xls 文件。
相关参考:
使用workbook.xlsx.load读取xls文件出错
Reading CSV file is giving error on browser console.
readFile error
解决方案:
暂时还没找到能解决使用 exceljs 上传 .csv 文件并在浏览器解析成 json 的技术方案。
先读完这几篇文档再看看:一文了解文件上传全过程(1.8w字深度解析,进阶必备), 流式上传文件