使用python从Excel工作表中提取图像 [英] Use python extract images from Excel sheets

查看:319
本文介绍了使用python从Excel工作表中提取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found some Python2 code to extract images from Excel files.

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

I have a very fundamental question: Where shall I specify the path of my target excel file?

还是仅对打开的活动Excel文件起作用?

Or does it only work with an active opened Excel file?

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文件中抓取图像:

You can grab images from existing Excel file like this:

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'):
            shape.Copy()
            image = ImageGrab.grabclipboard()
            image.save('{}.jpg'.format(i+1), 'jpeg')

这篇关于使用python从Excel工作表中提取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆