【问题标题】:how to add a png file into a word document in python 3如何在python 3中将png文件添加到word文档中
【发布时间】:2020-01-17 03:59:07
【问题描述】:

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

很抱歉,如果我没有提到我应该有的东西,我在提问方面还是个新手。

【问题讨论】:

  • docx 如python-docx?项目页面声称它适用于 Python 2 和 3。
  • 是的,对不起,我会编辑它以使其更清晰
  • 你怎么知道 python-docx 只适用于 2.x?你做pip install python-docx的时候是不是安装失败了?当您执行import docx 时,它是否无法运行?它运行了吗,但行为方式出乎你的意料?请提供更多详细信息。
  • 好的,会在问题中
  • 你有一些 anaconda python 环境正在运行吗?如果不安装版本为 3.7 或更高版本的 anacona python 以及使用 python==2.7.14 左右的替代环境...您再次安装 python-docx 瞧...您需要大约 1.5 小时才能完成它;- )

标签: python python-3.x python-docx


【解决方案1】:

正确的 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 文件在这里:

【讨论】:

  • 我打算在anaconda中尝试一下,但是是的,我看到了网站,还是谢谢你:)
  • .. 好读 :-) 如果你想测试运行实验包的小提示。例如:conda create -n py36test python=3.6conda activate py36test 保持你的基础环境干净:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-15
  • 2012-03-04
  • 1970-01-01
相关资源
最近更新 更多