如何在 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。
下面是 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 文件在这里:
目标是将我拥有的 png 图像复制到文档(最好是 word 文档)中。我找到了 python-docx
,但这只适用于 python 2.x(已成功下载),但没有 运行。我唯一能在
对不起,如果我没有提到任何我应该知道的,我在提问方面还是个新手。
正确的 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 文件在这里: