如何使用 openpyxl 查找包含图像的单元格
How to find cells that contain images with openpyxl
我正在遍历工作簿中的每个单元格。出于某种原因,当 openpyxl 遍历包含图像的工作表时,图像被删除。如何解决这个问题?
我正在寻找一种方法来传递具有图像的单元格。
我不处于 read_only
模式,并且不想进入,因为我正在修改工作表。
像这样的东西对我最有用:
if cell is image:
pass
documentation 明确指出这将发生:
Warning
openpyxl does currently not read all possible items in an Excel file so images and charts will be lost from existing files if they are opened and saved with the same name.
[强调我的]
这与图像和图表不是常规单元格内容并且存储在文件的单独部分中这一事实有关。有写入图片的功能,但没有读取图片的功能。
您的选择是等待开发人员实现该功能、使用不同的库或自己提供补丁。
一个更现实的选择可能是将您所做的修改写入另一个文件,然后手动将非图像部分复制回原始文件。
理想情况下,这在您的情况下似乎是正确的,您可以从电子表格外部获得图像。在这种情况下,您可以在写入文件时将它们重新插入。
另一个可能的解决方法是将原始文件作为 zip 文件打开并从中提取图像(手动或以编程方式)。
https://pypi.org/project/openpyxl-image-loader/
from openpyxl import load_workbook
from openpyxl_image_loader import SheetImageLoader
# Load your workbook and sheet as you want, for example
wb = load_workbook('path_to_file.xlsx')
sheet = wb['required_sheet']
# Put your sheet in the loader
image_loader = SheetImageLoader(sheet)
# And get image from specified cell
image = image_loader.get('A3')
# Image now is a Pillow image, so you can do the following
image.show()
# Ask if there's an image in a cell
if image_loader.image_in('A4):
print("Got it!")
我正在遍历工作簿中的每个单元格。出于某种原因,当 openpyxl 遍历包含图像的工作表时,图像被删除。如何解决这个问题?
我正在寻找一种方法来传递具有图像的单元格。
我不处于 read_only
模式,并且不想进入,因为我正在修改工作表。
像这样的东西对我最有用:
if cell is image:
pass
documentation 明确指出这将发生:
Warning
openpyxl does currently not read all possible items in an Excel file so images and charts will be lost from existing files if they are opened and saved with the same name.
[强调我的]
这与图像和图表不是常规单元格内容并且存储在文件的单独部分中这一事实有关。有写入图片的功能,但没有读取图片的功能。
您的选择是等待开发人员实现该功能、使用不同的库或自己提供补丁。
一个更现实的选择可能是将您所做的修改写入另一个文件,然后手动将非图像部分复制回原始文件。
理想情况下,这在您的情况下似乎是正确的,您可以从电子表格外部获得图像。在这种情况下,您可以在写入文件时将它们重新插入。
另一个可能的解决方法是将原始文件作为 zip 文件打开并从中提取图像(手动或以编程方式)。
https://pypi.org/project/openpyxl-image-loader/
from openpyxl import load_workbook
from openpyxl_image_loader import SheetImageLoader
# Load your workbook and sheet as you want, for example
wb = load_workbook('path_to_file.xlsx')
sheet = wb['required_sheet']
# Put your sheet in the loader
image_loader = SheetImageLoader(sheet)
# And get image from specified cell
image = image_loader.get('A3')
# Image now is a Pillow image, so you can do the following
image.show()
# Ask if there's an image in a cell
if image_loader.image_in('A4):
print("Got it!")