[英]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 文件在这里:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.