python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Excel按行提取图片

Python从Excel中按行提取图片的实现方法

作者:RumIV

在Excel表格中批量导出图片,并按行首字段命名保存,是许多办公场景的刚需,本文提供两个完整可运行的Python版本,两个版本均实现了从Excel中按行提取图片,需要的朋友可以参考下

前言

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

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

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

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

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质量。适合需要统一格式、减小体积的场景。

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/

四、使用步骤(通用)

安装依赖

pip install openpyxl pillow

准备Excel文件

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

运行脚本

python extract_images.py   # 或 extract_as_jpg.py

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

五、注意事项

六、扩展建议

七、总结

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

以上就是Python从Excel中按行提取图片的方法实现的详细内容,更多关于Python Excel按行提取图片的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文