我只是在用Python创建一些自动化程序,其中的结果必须保存在Excel文件中.我遇到的问题是更新这些结果,特别是图像. 我找不到一种方法来删除或更新以前保存在特定单元格中的图像.
我知道如何删除所有图像,但这不是我需要的;其他图像无法删除.我只需要清除一个特定的单元格,然后粘贴不同的图像.example here个 作为一个虚构的例子,我如何在不接触其他单元格的情况下完全清除单元格C6;而不仅仅是清除我知道如何做的文本?
我只是在用Python创建一些自动化程序,其中的结果必须保存在Excel文件中.我遇到的问题是更新这些结果,特别是图像. 我找不到一种方法来删除或更新以前保存在特定单元格中的图像.
我知道如何删除所有图像,但这不是我需要的;其他图像无法删除.我只需要清除一个特定的单元格,然后粘贴不同的图像.example here个 作为一个虚构的例子,我如何在不接触其他单元格的情况下完全清除单元格C6;而不仅仅是清除我知道如何做的文本?
如果你想用Python来做这件事,Openpyxl可以用来读取和删除工作表中所需的图像.
还有其他Python模块也可以实现这一点,Openpyxl不需要Excel,可以在Windows和Linux上运行.
具体的实现可能取决于用什么来确定要删除的映像.在本例中,我使用的是完整的单元格文本,但是,与文本或单元格坐标的部分匹配可能就足够了.
在所选工作表的示例中,我们遍历图像以提取每个图像的单元格坐标.使用坐标查找单元格文本,然后删除图像并清除文本.
The code uses your example Sheet as the basis.
ws._images
is a Python List of the images in the Sheet. An image can be then deleted from the list by its index.
Note the deletion in the code is followed by a 'break' since deleting an image in while looping the image list will affect the order so the example deletes for only one cell and exits. If more than one image is to be found and deleted, creating a list of the cells to delete and running the deletes from that would be better.
Example Code
import openpyxl
import string
excelfile = 'imagefile.xlsx'
wb = openpyxl.load_workbook(excelfile)
ws = wb['Sheet1']
### Set the cell to clear image from
cell_to_delete = 'C9'
### Check for images in Sheet
for idx, image in enumerate(ws._images):
row = image.anchor._from.row + 1
col = string.ascii_uppercase[image.anchor._from.col]
cell = ws[f'{col}{row}']
print(f"Image in cell {cell.coordinate}. Cell text: '{cell.value}'")
if cell.value.lower() == f"some text in {cell_to_delete}".lower():
### Delete image from cell
del ws._images[idx]
### Clear contents from cell
cell.value = None
break
wb.save(excelfile)
还要注意,代码依赖于图像的准确单元格锚点,即如果图像左上角的点稍微位于另一个单元格中,则该单元格将被视为锚点.例如,在屏幕截图中使用单元格C9中的图像.如果图像稍微偏左并侵占了单元格‘B9’,那么这将是图像锚定单元格,即使图像的大部分位于单元格‘C9’.