python - 使用python从Excel工作表中提取图像

标签 python excel image

我找到了一些 Python2 代码来从 Excel 文件中提取图像。

我有一个非常基本的问题:我应该在哪里指定路径 我的目标 excel 文件?

或者它只适用于事件的打开的 Excel 文件?

import win32com.client       # Need pywin32 from pip
from PIL import ImageGrab    # Need PIL as well
import os

excel = win32com.client.Dispatch("Excel.Application")
workbook = excel.ActiveWorkbook

wb_folder = workbook.Path
wb_name = workbook.Name
wb_path = os.path.join(wb_folder, wb_name)

#print "Extracting images from %s" % wb_path
print("Extracting images from", wb_path)

image_no = 0

for sheet in workbook.Worksheets:
    for n, shape in enumerate(sheet.Shapes):
        if shape.Name.startswith("Picture"):
            # Some debug output for console
            image_no += 1
            print("---- Image No. %07i ----", image_no)

            # Sequence number the pictures, if there's more than one
            num = "" if n == 0 else "_%03i" % n

            filename = sheet.Name + num + ".jpg"
            file_path = os.path.join (wb_folder, filename)

            #print "Saving as %s" % file_path    # Debug output
            print('Saving as ', file_path)

            shape.Copy() # Copies from Excel to Windows clipboard

            # Use PIL (python imaging library) to save from Windows clipboard
            # to a file
            image = ImageGrab.grabclipboard()
            image.save(file_path,'jpeg')

最佳答案

您可以像这样从现有的 Excel 文件中抓取图像:

from PIL import ImageGrab
import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(r'C:\Users\file.xlsx')

for sheet in workbook.Worksheets:
    for i, shape in enumerate(sheet.Shapes):
        if shape.Name.startswith('Picture'):  # or try 'Image'
            shape.Copy()
            image = ImageGrab.grabclipboard()
            image.save('{}.jpg'.format(i+1), 'jpeg')

关于python - 使用python从Excel工作表中提取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13448508/

相关文章:

javascript - 为 Rails 站点安装 Bootstrap 图片库时遇到问题

python - python中SSL客户端的正确证书目的是什么?

python - 十进制模块 : rounding

python - 如何正确解码 Django HTML 模板中引用的可打印编码

python - 使用 xlwings 和 python 复制工作表

excel - 为什么不能在excel中过滤带有〜符号的记录

python - 如何使用 pandas 在 Excel 工作表中的同一个图形上绘制多个数据框?

php - 在(纯)PHP/MySQL 中查找类似图像

C++图像过滤算法

python - 在 Plotly 中的图形顶部添加饼图