Excel提取图片并自动上传到接口
在实际项目中,我们可能经常会遇到需要批量从Excel文件(.xlsx)中提取图片并上传到特定接口的场景。今天,我就详细介绍一下如何使用Python实现这一功能,本文会手把手教你搭建一个完整的解决方案。
一、整体需求
我们要实现的功能主要有三个步骤:
- 从Excel文件中提取所有嵌入的图片。
- 将图片文件上传到指定的API接口。
- 支持从本地文件或网络链接读取Excel文件。
二、实现原理
Excel文件(.xlsx
格式)本质是一个压缩的ZIP文件,图片都存储在内部路径xl/media
下。因此我们使用Python的zipfile
库来解压并提取其中的图片文件。
上传图片则通过requests
库实现POST请求完成文件上传。
三、核心代码实现
步骤1:从Excel提取图片
from zipfile import ZipFile
import mimetypes
import osdef extract_images_from_excel(xlsx_path):images = []with ZipFile(xlsx_path, 'r') as zf:for name in zf.namelist():if name.startswith("xl/media/"):raw = zf.read(name)fname = os.path.basename(name)mime, _ = mimetypes.guess_type(fname)mime = mime or "application/octet-stream"images.append((fname, raw, mime))return images
步骤2:上传图片到接口
import requests
import iodef upload_image(filename, file_bytes, mime_type, token, upload_url):headers = {"authorization": f"Bearer {token}"}files = {"file": (filename, io.BytesIO(file_bytes), mime_type)}response = requests.post(upload_url, headers=headers, data=data, files=files)response.raise_for_status()return response.json()
步骤3:支持Excel文件下载(可选)
import requests
import os
from urllib.parse import urlparsedef download_excel(url, save_dir="downloads"):os.makedirs(save_dir, exist_ok=True)fname = os.path.basename(urlparse(url).path) or "file.xlsx"path = os.path.join(save_dir, fname)resp = requests.get(url)resp.raise_for_status()with open(path, "wb") as f:f.write(resp.content)return path
四、完整使用案例
下面是完整的使用脚本,集成了上述所有功能,支持本地文件和网络下载:
import sys
import redef main(source):if re.match(r'^https?://', source):excel_path = download_excel(source)else:excel_path = sourceimages = extract_images_from_excel(excel_path)print(f"共找到{len(images)}张图片,即将上传...")for fname, content, mime in images:result = upload_image(filename=fname,file_bytes=content,mime_type=mime,token="你的接口token",upload_url="你的上传URL")if result.get("success"):print(f"上传成功:{fname} 链接为 {result['data']['fileUrl']}")else:print(f"上传失败:{fname}")if __name__ == "__main__":source = sys.argv[1]main(source)
使用示例:
python script.py /path/to/file.xlsx
python script.py https://example.com/file.xlsx
五、小结
通过以上介绍,相信你已经掌握了如何从Excel中批量提取图片并上传至指定接口的方法。这种方式简单易用且可扩展性强,在自动化处理场景中尤其有用。
希望本文能够帮到你,如果有任何问题,欢迎在评论区与我交流!