我只是在用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’.

Python相关问答推荐

Pandas read_jsonfuture 警告:解析字符串时,to_datetime与单位的行为已被反对

使用Python和PRNG(不是梅森龙卷风)有效地生成伪随机浮点数在[0,1)中均匀?

Python panda拆分列保持连续多行

不允许AMBIMA API请求方法

在上下文管理器中更改异常类型

如何计算列表列行之间的公共元素

如何处理嵌套的SON?

Django管理面板显示字段最大长度而不是字段名称

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

如何使用html从excel中提取条件格式规则列表?

使可滚动框架在tkinter环境中看起来自然

优化pytorch函数以消除for循环

在Mac上安装ipython

如何使用Python以编程方式判断和检索Angular网站的动态内容?

无法在Docker内部运行Python的Matlab SDK模块,但本地没有问题

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

在Python中使用yaml渲染(多行字符串)

在二维NumPy数组中,如何 Select 内部数组的第一个和第二个元素?这可以通过索引来实现吗?

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion