use*_*Geo 7 python ms-word python-docx
如何在 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))
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
有了这样的东西
#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))
Run Code Online (Sandbox Code Playgroud)
它似乎对我有用,但非常感谢你的问题,它让我走上了正确的轨道,不仅很难删除图像,当我添加新图像时,它是向下换行的。但我的代码有点紧凑,解决了这两个问题。
谢谢!