python - 使用python从Excel表格中提取图像
问题描述
我找到了一些 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')
推荐阅读
- docker - Docker swarm 容器连接问题
- c# - 我在制作 RDLC 报告时尝试通过 C# 手动添加数据源时出现错误
- mysql - sqldump 以某种方式查找表而不是完整备份?
- javascript - 一组输入和一个文本区域至少需要一个值
- angular-material - mat-sort-header 未显示
- django - Django 应用部署 digitalocean 卡在 nginx 主页
- excel - IF 单元格 = 特定文本,在另一个单元格中显示分配的数字作为结果
- codeigniter - 在代码点火器中将英语输入转换为乌尔都语和土耳其语
- android - 自定义 EditText 默认光标位置
- php - 准备好的语句 PHP OOP