gpt4 book ai didi

Python-docx 在表中查找和替换图像

转载 作者:行者123 更新时间:2023-12-04 12:45:21 46 4
gpt4 key购买 nike

如何在 MS 文档表中找到现有图像并将其替换为新图像?使用此代码可以找到图像的表格单元格/位置并添加新图像,但它不会替换旧图像。

from docx import Document
from docx.shared import Inches


doc = docx.Document('myWordDoc.docx')

tables = doc.tables

# Find existing image and remove it then add new image

img = tables[0].rows[0].cells[0].add_paragraph()
r = img.add_run()
r.add_picture('/tmp/foo.jpg', width=Inches(2.5))

这可能与 python-docx 模块或任何其他模块吗?

最佳答案

我替换了你的最后 3 行代码:

img = tables[0].rows[0].cells[0].add_paragraph()
r = img.add_run()
r.add_picture('/tmp/foo.jpg', width=Inches(2.5))

像这样的东西
#This seams to clear the content in my cell
tables[0].rows[0].cells[0]._element.clear_content()

#Then when the image is inserted to the cell it is not placed one linefeed down.
img = tables[0].rows[0].cells[0].add_paragraph().add_run().add_picture('Image.png', width=Inches(0.4))

它对我有用,但非常感谢你的问题,它让我走上了正确的轨道,不仅很难删除图像,当我添加新图像时,它是一个换行符。但是我的代码有点紧凑,解决了这两个问题。

谢谢!

关于Python-docx 在表中查找和替换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551138/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com