第一步:安装xlsx;
npm install xlsx
第二步:将文件解析成json
2.1使用并获取excel中sheet1、sheet2的对应数据
const workbook = (await excelToJsonAll(e.file)) || [];
const sheetNameArr = workbook.SheetNames.filter((item) =>
item.includes('_Schema'),
);
let sheet1, sheet2;
if (sheetNameArr.length > 0) {
// 解析出来包含_Schema的sheet
sheet1 = getIndexSheetData(workbook, 1);
sheet2 = getIndexSheetData(workbook, 2);
} else {
sheet1 = getIndexSheetData(workbook, 0);
sheet2 = getIndexSheetData(workbook, 1);
}
2.2封装解析方法
// 从工作簿中获取第几个工作表的数据
export function getIndexSheetData(
workbook: WorkBook,
index: number = 0,
): any[] {
const firstSheetName = workbook.SheetNames[index];
if (!firstSheetName) {
throw new Error('No sheets found in the workbook');
}
const workSheet = workbook.Sheets[firstSheetName];
if (!workSheet) {
throw new Error(`Sheet "${firstSheetName}" not found in the workbook`);
}
return utils.sheet_to_json(workSheet);
}
// 读取 Excel 文件并转换为 JSON 数据
export async function excelToJsonAll(file: File) {
const buffer = await file.arrayBuffer(); // 读取文件并转换为 ArrayBuffer
const data = new Uint8Array(buffer);
const workbook = read(data, { type: 'array' });
// 对第一个进行校验是否有
const firstSheetName = workbook.SheetNames[0];
if (!firstSheetName) {
throw new Error('No sheets found in the workbook');
}
const workSheet = workbook.Sheets[firstSheetName];
if (!workSheet) {
throw new Error(`Sheet "${firstSheetName}" not found in the workbook`);
}
return workbook;
}
第三步:获取excel的数据
let data=[]
for (const material of sheet1) {
const value= toString(material['表头文字']);
....
data.push(value)
}