gpt4 book ai didi

python - 如何在python 3中将png文件添加到word文档中

转载 作者:行者123 更新时间:2023-11-30 21:52:59 25 4
gpt4 key购买 nike

目标是将我的 png 图像复制到文档中(最好是 Word 文档)。我找到了 python-docx,但这只适用于 python 2.x(已成功下载),但它没有运行。我唯一能在 this 中找到关于它的信息。堆栈溢出问题。它被标记为 python-2.7。我不介意图片是否必须与 word 文档位于同一目录中。

抱歉,如果我没有提及任何我应该提及的内容,我在提问方面还很陌生。

最佳答案

正确的 python-docx 安装:

  • 从命令行:pip install python-docx

您应该获得最新的 0.8.10。大约 5.5mb 大。

下面是 here 使用的 python-docx 示例代码。查看文件所在的位置。如果您根据自己的喜好进行调整,那么您应该获得一个 docx 文件。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
'first item in ordered list', style='List Number'
)

document.add_picture('D:\test\monty-truth.png', width=Inches(1.25))

records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc

document.add_page_break()

document.save('D:\test\demo.docx')

monthy-truth.png 文件位于此处:

image

关于python - 如何在python 3中将png文件添加到word文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59776318/

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