版本:"xlsx": "^0.17.0"(package.json)
import * as XLSX from 'xlsx'
const dataArr = ref<any>([])
const tableColumn = ref<any>([])
//获取流文件接口按钮
const test = async () => {
const data = await fetch('接口url地址', {
method: 'GET',
})
if (data.status !== 200) {
throw new Error('网络错误,无法获取Excel文件')
}
// 从响应中获取二进制数据
const arrayBuffer = await data.arrayBuffer()
// 使用xlsx库解析Excel数据
const workbook = XLSX.read(arrayBuffer, { type: 'buffer' })
// 获取第一个工作表
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
// 将工作表转换为JSON数组
const jsonData = XLSX.utils.sheet_to_json(worksheet)
const headers = getHeader(worksheet)
setTable(headers, jsonData)
}
//解析出excel数据
const setTable = (headers: any, excellist: any) => {
const tableTitleData: any = [] // 存储表格表头数据
const tableMapTitle: any = {} // 设置表格内容中英文对照用
headers.forEach((_: any, i: any) => {
tableMapTitle[_] = 'prop' + i
tableTitleData.push({
prop: 'prop' + i,
label: _,
})
})
console.log('tableTitleData', tableTitleData)
// 映射表格内容属性名为英文
const newTableData: any = []
excellist.forEach((_: any) => {
const newObj = {}
Object.keys(_).forEach((key) => {
newObj[tableMapTitle[key]] = _[key]
})
newTableData.push(newObj)
})
console.log('headers', headers);
console.log('newTableData', newTableData)
tableColumn.value = tableTitleData
dataArr.value = newTableData
}
//获取excel表头
const getHeader = (worksheet: any) => {
const headers = []
const range = XLSX.utils.decode_range(worksheet['!ref']) // worksheet['!ref'] 是工作表的有效范围
let C
/* 获取单元格值 start in the first row */
const R = range.s.r // 行 // C 列
let i = 0
for (C = range.s.c; C <= range.e.c; ++C) {
var cell = worksheet[XLSX.utils.encode_cell({ c: C, r: R })] /* 根据地址得到单元格的值find the cell in the first row */
var hdr = 'UNKNOWN' + C // 如果有空表头,会替换为您想要的默认值replace with your desired default
// XLSX.utils.format_cell 生成单元格文本值
if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
if (hdr.indexOf('UNKNOWN') > -1) {
if (!i) {
hdr = '__EMPTY'
} else {
hdr = '__EMPTY_' + i
}
i++
}
headers.push(hdr)
}
return headers
}
<el-button type="primary" class="back" @click="test">测试</el-button>
<el-table v-if="dataArr.length" max-height="600" :data="dataArr" border style="width: 100%">
<el-table-column :prop="item.prop" :label="item.label" v-for="(item, i) in tableColumn" :key="i">
</el-table-column>
</el-table>