工具类文件
javascript
// fileUtils.ts
import { ref } from 'vue';
import * as xlsx from 'xlsx';
interface RowData {
[key: string]: any;
}
export const tableData = ref<RowData[]>([]);
export async function handleFileSelect(url: string): Promise<void> {
try {
const response = await fetch(url);
const blob = await response.blob();
const reader = new FileReader();
reader.onload = (e: ProgressEvent<FileReader>) => {
if (e.target && e.target.result) {
const data = new Uint8Array(e.target.result as ArrayBuffer);
const workbook = xlsx.read(data, { type: 'array' });
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 }) as any[][];
// 提取标题并保持其顺序
const headers = jsonData[0];
console.log('Extracted Headers:', headers);
// 处理行(从索引1开始跳过标题)
jsonData.slice(1).forEach((row) => {
const rowData: RowData = {};
headers.forEach((header, index) => {
rowData[header] = row[index];
});
tableData.value.push(rowData);
});
console.log('Processed Table Data:', tableData.value);
}
};
reader.readAsArrayBuffer(blob);
} catch (error) {
console.error('获取或读取文件时出错:', error);
}
}
调用方法
javascript
const url ='https://xxxxx.xlsx';
await handleFileSelect(url);