gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:59:16 25 4
gpt4 key购买 nike

我找到了一些 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com