【Python】从Excel中按行提取图片

文章目录

在Excel表格中批量导出图片,并按行首字段命名保存,是许多办公场景的刚需。本文提供两个完整可运行的Python版本:

  • 版本一:保持图片原始格式(PNG、JPG等各自保留)
  • 版本二:统一将所有图片转换为JPG格式(节省空间、格式统一)

两个版本均实现了:按工作表分文件夹 → 根据图片所在行的A列值命名 → 自动处理重名和非法字符。

一、版本一:保持原始格式

该版本完全保留图片原始格式(.png / .jpg / .gif等),其他功能完整。

python 复制代码
import openpyxl
from PIL import Image as PILImage
import io
import os


def extract_images_from_excel(excel_path, output_dir=None):
    """
    按行提取 Excel 中的图片,存储到以 Sheet 名称命名的文件夹下,
    图片命名为该行第一个字段的值(即A列),保持原始格式。
    """
    if output_dir is None:
        output_dir = os.path.dirname(os.path.abspath(excel_path))

    os.makedirs(output_dir, exist_ok=True)

    wb = openpyxl.load_workbook(excel_path)
    extracted_count = 0

    for sheet_name in wb.sheetnames:
        ws = wb[sheet_name]
        print(f"处理工作表: {sheet_name}")

        safe_sheet_name = "".join(
            c for c in sheet_name if c not in r'\/:*?"<>|'
        ).strip()
        sheet_dir = os.path.join(output_dir, safe_sheet_name)
        os.makedirs(sheet_dir, exist_ok=True)

        # 收集每行A列的值
        row_first_cell = {}
        for row in range(1, ws.max_row + 1):
            cell_value = ws.cell(row=row, column=1).value
            if cell_value is not None:
                row_first_cell[row] = str(cell_value)

        for image in ws._images:
            anchor = image.anchor
            if hasattr(anchor, '_from'):
                row_num = anchor._from.row + 1
            elif hasattr(anchor, 'row'):
                row_num = anchor.row + 1
            else:
                print(f"  ⚠️ 无法确定图片行号,跳过")
                continue

            first_cell_value = row_first_cell.get(row_num, None)
            if first_cell_value is None:
                print(f"  ⚠️ 第{row_num}行第一个字段为空,跳过")
                continue

            safe_name = "".join(
                c for c in first_cell_value if c not in r'\/:*?"<>|'
            ).strip()
            if not safe_name:
                safe_name = f"row_{row_num}"

            img_data = image._data()
            img = PILImage.open(io.BytesIO(img_data))

            # 获取原始格式
            img_format = img.format.lower() if img.format else 'png'

            filename = f"{safe_name}.{img_format}"
            filepath = os.path.join(sheet_dir, filename)

            counter = 1
            base_name = safe_name
            while os.path.exists(filepath):
                filename = f"{base_name}_{counter}.{img_format}"
                filepath = os.path.join(sheet_dir, filename)
                counter += 1

            img.save(filepath)
            extracted_count += 1
            print(f"  ✅ 第{row_num}行 -> {safe_sheet_name}/{filename}")

    print(f"\n🎉 完成!共提取 {extracted_count} 张图片,保存至: {output_dir}")


if __name__ == '__main__':
    excel_path = 'cards.xlsx'   # 修改为你的文件
    extract_images_from_excel(excel_path, output_dir='images')

二、版本二:统一存储为JPG格式

该版本将所有提取的图片统一转换为JPG格式(背景自动填充白色以处理透明通道),可设置JPG质量。适合需要统一格式、减小体积的场景。

python 复制代码
import openpyxl
from PIL import Image as PILImage
import io
import os


def extract_images_as_jpg(excel_path, output_dir=None, jpg_quality=85):
    """
    按行提取 Excel 中的图片,统一转换为 JPG 格式存储。
    参数:
        excel_path: Excel 文件路径
        output_dir: 输出根目录
        jpg_quality: JPG 压缩质量 (1-100),默认85
    """
    if output_dir is None:
        output_dir = os.path.dirname(os.path.abspath(excel_path))

    os.makedirs(output_dir, exist_ok=True)

    wb = openpyxl.load_workbook(excel_path)
    extracted_count = 0

    for sheet_name in wb.sheetnames:
        ws = wb[sheet_name]
        print(f"处理工作表: {sheet_name}")

        safe_sheet_name = "".join(
            c for c in sheet_name if c not in r'\/:*?"<>|'
        ).strip()
        sheet_dir = os.path.join(output_dir, safe_sheet_name)
        os.makedirs(sheet_dir, exist_ok=True)

        # 收集每行A列的值
        row_first_cell = {}
        for row in range(1, ws.max_row + 1):
            cell_value = ws.cell(row=row, column=1).value
            if cell_value is not None:
                row_first_cell[row] = str(cell_value)

        for image in ws._images:
            anchor = image.anchor
            if hasattr(anchor, '_from'):
                row_num = anchor._from.row + 1
            elif hasattr(anchor, 'row'):
                row_num = anchor.row + 1
            else:
                print(f"  ⚠️ 无法确定图片行号,跳过")
                continue

            first_cell_value = row_first_cell.get(row_num, None)
            if first_cell_value is None:
                print(f"  ⚠️ 第{row_num}行第一个字段为空,跳过")
                continue

            safe_name = "".join(
                c for c in first_cell_value if c not in r'\/:*?"<>|'
            ).strip()
            if not safe_name:
                safe_name = f"row_{row_num}"

            img_data = image._data()
            img = PILImage.open(io.BytesIO(img_data))

            # ----- 转换为 JPG 的关键代码 -----
            # 若图片为 RGBA(带透明通道),需转换为 RGB(白色背景)
            if img.mode in ('RGBA', 'LA', 'P'):
                # 创建白色背景
                background = PILImage.new('RGB', img.size, (255, 255, 255))
                # 将原图粘贴到背景(使用透明通道作为掩码)
                if img.mode == 'P':
                    img = img.convert('RGBA')
                background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
                img = background
            elif img.mode != 'RGB':
                img = img.convert('RGB')
            # -----------------------------

            filename = f"{safe_name}.jpg"
            filepath = os.path.join(sheet_dir, filename)

            counter = 1
            base_name = safe_name
            while os.path.exists(filepath):
                filename = f"{base_name}_{counter}.jpg"
                filepath = os.path.join(sheet_dir, filename)
                counter += 1

            # 保存为 JPG,可指定质量
            img.save(filepath, 'JPEG', quality=jpg_quality)
            extracted_count += 1
            print(f"  ✅ 第{row_num}行 -> {safe_sheet_name}/{filename} (JPG质量={jpg_quality})")

    print(f"\n🎉 完成!共提取 {extracted_count} 张图片,已统一为JPG格式,保存至: {output_dir}")


if __name__ == '__main__':
    excel_path = 'cards.xlsx'   # 修改为你的文件
    extract_images_as_jpg(excel_path, output_dir='images_jpg', jpg_quality=85)

三、两个版本的核心区别

特性 版本一(原格式) 版本二(统一JPG)
输出扩展名 .png / .jpg / .gif 等原样保留 统一为 .jpg
透明背景处理 保留原图(PNG透明通道) 白色背景填充
压缩控制 无(原样保存) 可调节 quality 参数
适用场景 需要保留原始质量/透明效果 统一浏览、减小体积
输出文件夹 images/ images_jpg/

四、使用步骤(通用)

  1. 安装依赖

    bash 复制代码
    pip install openpyxl pillow
  2. 准备Excel文件

    • 确保图片是"嵌入"到单元格中的(而非浮动链接)。
    • 每个含图片的行,A列 必须有值,该值将作为图片文件名。
  3. 选择版本并修改路径

    将代码末尾的 excel_path = 'cards.xlsx' 改为实际文件路径,可修改 output_dir

  4. 运行脚本

    bash 复制代码
    python extract_images.py   # 或 extract_as_jpg.py
  5. 结果

    在输出目录下会按工作表名称创建子文件夹,图片按 A列值 命名存放。

五、注意事项

  • 图片定位:脚本依赖 openpyxl 的图片锚点属性,对于合并单元格或跨行图片可能定位不准,建议将图片完整置于某一行内。
  • 命名冲突 :同一工作表中不同行的 A列值相同时,会自动添加 _1_2 后缀。
  • 非法字符 :文件名中的 / \ : * ? " < > | 会被自动去除。
  • JPG 版本:原图为 GIF 动图时,只会提取第一帧并转为 JPG;原图为 CMYK 模式会自动转为 RGB。

六、扩展建议

  • 修改命名列 :将 column=1 改为 column=2 即可使用B列命名。
  • 批量处理多个Excel:可在外层增加循环,依次调用函数。
  • 支持更多输出格式 :在版本二中将 'JPEG' 改为 'PNG' 即可输出 PNG,但体积较大。
  • 保留透明通道转PNG:若希望统一为 PNG 并保留透明,可将版本二的转换代码去掉,直接保存为 PNG。

七、总结

本文提供了两个完整、可直接运行的 Python 脚本,分别满足"原格式保留"和"统一转 JPG"的常见需求。你只需要替换文件路径即可运行,大大提升从 Excel 批量导出图片的效率。选择适合自己的版本,开始自动化办公吧!

相关推荐
张二娃同学1 小时前
第08篇_RNN_LSTM_GRU序列模型
人工智能·python·rnn·深度学习·神经网络·gru·lstm
财经资讯数据_灵砚智能1 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月13日
大数据·人工智能·python·信息可视化·语言模型·自然语言处理
啃臭1 小时前
AOP和反射
java·spring boot
西凉的悲伤1 小时前
java 使用PNG图片隐写文件
java·图片隐写·png
有梦想的小何1 小时前
Cursor AI 编程实战(篇一):Prompt 与案例总结
java·linux·prompt·ai编程
我鑫如一1 小时前
专业的AI API中转站厂家
人工智能·python
如竟没有火炬1 小时前
接雨水22
数据结构·python·算法·leetcode·散列表
消晨消晨1 小时前
Pytorch初上手——Dataset自定义数据集与Dataloader数据加载器
人工智能·pytorch·python
小白学大数据2 小时前
均线选股策略研究:基于 Python 数据分析实现
人工智能·python·数据分析