繁体   English   中英

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

[英]how to add a png file into a word document in python 3

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

对不起,如果我没有提到我应该拥有的任何东西,我在提问方面仍然相当陌生。

正确的python-docx安装:

  • 从命令行: pip install python-docx

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

以下是此处使用的 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 文件在这里:

图片

我建议您查看以下链接:

使用 Python 在文档中的特定位置添加图像

希望这有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM