本文介绍如何使用 JavaScript(配合 SheetJS)读取含 image(图片 URL)和 name 列的 Excel 文件,将每行图片加载为 Base64 字符串,并与对应名称组合成 JSON 对象数组。
本文介绍如何使用 javascript(配合 sheetjs)读取含 `image`(图片 url)和 `name` 列的 excel 文件,将每行图片加载为 base64 字符串,并与对应名称组合成 json 对象数组。
在前端处理 Excel 数据时,若需将图片字段(通常为可访问的 HTTP/HTTPS 图片链接)与文本字段(如 name)一并导出为结构化 JSON,关键在于:正确解析 Excel 表格、定位列索引、异步加载并编码图片资源。以下是一个完整、健壮、可集成到 React 或纯 JS 项目的解决方案。
import * as XLSX from 'xlsx'; // 推荐通过 npm install xlsx 引入const handleFormSubmit = async (field, e) => { const file = e.target.files?.[0]; if (!file) return; try { const arrayBuffer = await file.arrayBuffer(); const data = new Uint8Array(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 }); if (jsonData.length < 2) { console.warn('Excel must contain at least header + one data row'); return; } const headers = jsonData[0]; const imageIndex = headers.indexOf('image'); const nameIndex = headers.indexOf('name'); if (imageIndex === -1 || nameIndex === -1) { throw new Error('Excel must have columns named "image" and "name"'); } const results = []; const promises = []; // 使用 Promise.all 确保所有图片加载完成后再返回结果 for (let i = 1; i < jsonData.length; i++) { const row = jsonData[i]; const name = row[nameIndex]; const imageUrl = row[imageIndex]; if (!imageUrl || typeof imageUrl !== 'string') continue; const promise = new Promise((resolve) => { const img = new Image(); img.crossOrigin = 'anonymous'; // 支持跨域图片(如 CDN) img.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; ctx.drawImage(img, 0, 0); const base64 = canvas.toDataURL('image/jpeg', 0.9); // 可选压缩质量 resolve({ image: base64, name }); }; img.onerror = () => { console.warn(`Failed to load image: ${imageUrl}`); resolve({ image: null, name }); // 或跳过该条目 }; img.src = imageUrl; }); promises.push(promise); } const finalResults = await Promise.all(promises); console.log('✅ Parsed JSON with images:', finalResults); // 此处可调用 API 提交 finalResults,或 setState 更新 UI return finalResults; } catch (err) { console.error('❌ Excel parsing or image conversion failed:', err); }};
通过本方案,您即可高效、可靠地将 Excel 中的图片链接批量转为内联 Base64 JSON,无缝对接后续上传、展示或 AI 处理流程。