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

标签 python python-3.x python-docx

目标是将我的 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/

相关文章:

Python:使用返回值查找错误原因

python - 将数据框列表转换(转置)为列

python - 将列添加到表的左侧 - Python docx

python-3.x - 使用 python-docx 在 Word 文档的页眉中添加 Logo

python - 如何使用 sklearn.preprocessing.normalize 规范化 DataFrame 的列?

php - 动态图像调整大小

python - 如何将 Python C 模块与 `ld` 链接。对 `__dso_handle' 的 undefined reference

python-3.x - 如何将浮点转换为任何浮点的 XE-Y 表示

python - 如何在单词完成后检测刽子手获胜

python - 如何在Python中将从PDF(使用textract)提取的文本写入docx文件