python读取excel中的图片

前言

现在大部分读取excel中的图片都是通过将xlsx文件压缩,然后读取,本文可以通过python的包来读取,相比之下代码更简洁更方便。

环境准备:

  • python3
  • pillow
pip install pillow
  • pypiwin32
pip install pypiwin32

代码

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')
excel.Quit()

注意事项

  • 有些xlsx文件可能读取不了,试试换成xls格式
  • 程序运行前不可以有其他程序打开excel文件

你可能感兴趣的:(Python)