工具类文件
- // 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);
- }
- }
复制代码 调用方法
- const url ='https://xxxxx.xlsx';
- await handleFileSelect(url);
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |