准备工作 - 下载 xlsx
npm install xlsx
下面直接上代码
<template>
<div>
<input type="file" accept=".xlsx, .xls" @change="handleClick">
</div>
</template>
<script lang='ts' setup>
import * as XLSX from 'xlsx'
const handleClick = async (e) => {
const res = await readerData(e.target.files[0])
console.log(res); // 获取的数据格式 { header: [], results: [{}] }
}
// 纯前端导入excel
const readerData = (rawFile) => {
return new Promise((resolve, reject) => {
// 创建一个文件读取的实例
const reader = new FileReader()
reader.onload = e => { // onload是加载完实例后执行(异步)
const data = e.target.result
const workbook = XLSX.read(data, { type: 'array' })
// 获取一张表的表名
const firstSheetName = workbook.SheetNames[0]
// 根据表名拿到表里面的内容
const worksheet = workbook.Sheets[firstSheetName]
// 解析成json
const results = XLSX.utils.sheet_to_json(worksheet)
// 获取表头数据
const header = getHeaderRow(worksheet)
resolve({ header, results })
}
// 读取成一个Buffer格式文件
reader.readAsArrayBuffer(rawFile)
})
}
// 获取表头数据
const getHeaderRow = (sheet) => {
const headers = []
const range = XLSX.utils.decode_range(sheet['!ref'])
let C
const R = range.s.r
/* start in the first row */
for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
/* find the cell in the first row */
let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
headers.push(hdr)
}
return headers
}
</script>