【问题标题】:how to export images to word file?如何将图片导出到word文件?
【发布时间】:2022-12-11 23:34:20
【问题描述】:

我正在编写一个将图像保存到 word 文件的脚本。我已经能够创建导出图像的功能。

def exp_images():  #export images to word file
    document = Document()
    paragraph = document.add_paragraph()
    script = paragraph.add_run()
    script.add_text('This is a test sentence')
    script.add_picture('image1.png', width=Inches(6.5))
    document.save('demo.docx')


if __name__ == "__main__":
    exp_images()

我面临的唯一问题是如何重复调用该函数,该函数必须将图像保存到新行,并且不得覆盖现有图像。 所以,我只需要帮助。 谢谢

【问题讨论】:

  • “将图像保存到新行”是什么意思?
  • @Cobra 假设您将图像保存在word 文件中,它被复制到ms-word 的第一行。然后,当您要将另一个图像导出到同一个 ms-word 文件时,新图像应保存在原始图像下方,而不是首先覆盖现有图像。
  • 在这种情况下,我建议您参考您用于 Microsoft Word 文档处理的模块的文档。这不是 Python 问题本身
  • 我包含 python 的原因是,我是在 python 的帮助下完成这个任务的。我有几张图片,我只想按顺序将它们保存到 word 文件中。

标签: python ms-word


【解决方案1】:

您可以将所有图像传递给您的函数,迭代所有图像,将它们附加到文档中,最后保存文档。

def exp_images(images):  # export images to word file
    document = Document()
    paragraph = document.add_paragraph()
    script = paragraph.add_run()
    script.add_text('This is a test sentence')

    # loop through a list of images and add each one to the document
    for image in images:
        # add a line break between the text and the image
        script.add_break(WD_BREAK.LINE)
        # add the image to the document
        script.add_picture(image, width=Inches(6.5))

    document.save('demo.docx')

if __name__ == "__main__":
    # call the exp_images function multiple times, loop through a list of images and add each one to the document
    images = ['image1.png', 'image2.png', 'image3.png']:
    exp_images(images)

【讨论】:

  • 试过了,确实有效,感谢您的帮助。我也在稍微调整一下逻辑,希望它能起作用。再次感谢。
  • @NischalKasera 很高兴它以某种方式帮助你
猜你喜欢
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
相关资源
最近更新 更多