安装依赖
npm i exceljs
实现
import ExcelJS from 'exceljs';
const { ctx }: any = getCurrentInstance();
const importFile = () => {
ctx.$refs.inputFile.click();
};
const getFiles = async () => {
const file = ctx.$refs.inputFile?.files?.[0];
if (!file) {
proxy.$ShowELmessage(proxy, '未选择文件', 'warning');
return;
}
try {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.load(file);
const sheet = workbook.getWorksheet(1);
if (!sheet) {
proxy.$ShowELmessage(proxy, '未找到工作表', 'error');
return;
}
const imageMaps: { [key: number]: string } = {};
const uploadImagePromises: Promise<void>[] = [];
sheet.getImages().forEach(image => {
const { range, imageId } = image;
if (range?.tl) {
const rowNumber = range.tl.nativeRow + 1;
const imageBuffer = workbook.getImage(Number(imageId)).buffer as Uint8Array;
const formData = new FormData();
const file = uint8ArrayToFile(imageBuffer, 'image.png', 'image/png');
formData.append('file', file);
const uploadPromise = uploadFile(formData).then(res => {
if (res.errcode === 0) {
imageMaps[rowNumber] = res.p2pdata;
} else {
proxy.$ShowELmessage(proxy, `上传第${rowNumber}行图片失败`, 'error');
}
});
uploadImagePromises.push(uploadPromise);
}
});
await Promise.all(uploadImagePromises);
const tableData: PurchaseDetail[] = [];
sheet.eachRow((row, rowIndex) => {
if (rowIndex > 1) {
tableData.push({
parameterText: row.getCell(4).value?.toString() || '',
parameterImg: imageMaps[rowIndex] || '',
});
}
});
console.log(tableData);
} catch (error: any) {
proxy.$ShowELmessage(proxy, `处理文件时出错: ${error.message}`, 'error');
} finally {
ctx.$refs.inputFile.value = '';
}
};
const uint8ArrayToFile = (uint8Array: Uint8Array, fileName: string, type: string) => {
const blob = new Blob([uint8Array], { type });
const file = new File([blob], fileName || 'file', { type });
return file;
}