如何使用Python创建Microsoft Word段落并插入图片?
介绍…
作为数据工程专家,我经常从测试人员手中收到Microsoft Word测试结果。哎呀!他们将从截图到非常长的段落中收集了如此多的信息。
另一天,测试团队请我帮忙编写程序来插入生成的文本和图像工具(由自动截图获取。本文不涉及)。
不同于其他文档,MS Word文档没有页面的概念,它以段落为单位工作,所以我们需要使用换行符和节来正确地划分文档。
如何做到这一点…
1. 首先安装Python-docx。
导入docx
# 创建新文档
WordDocx = docx.Document()
# 我的段落
Paragraph = WordDocx.add_paragraph('1. Hello World, Some Sample Text Here...')
run = Paragraph.add_run()
# 带换行的段落
run.add_break(docx.text.run.WD_BREAK.LINE)
# 添加更多内容
Paragraph.add_run('2. I have just written my 2nd line and I can write more..')
# 最后保存文档
WordDocx.save('My_Amazing_WordDoc.docx')
2. 现在让我们程序化地检查内容是否正确。
doc = docx.Document('My_Amazing_WordDoc.docx')
print(f"output \n *** Document has {len(doc.paragraphs)} - paragraphs")
for paragraph_number, paragraph in enumerate(doc.paragraphs):
if paragraph.text:
print(f"\n {paragraph.text}")
输出
*** Document has 1 - paragraphs
1. Hello World, Some Sample Text Here...
2. I have just written my 2nd line and I can write more..
3. 现在我们将向文档添加图像。首先,我们需要寻找一张图片。我已经从unsplash.com下载了一张没有版权问题的图片。请务必小心操作您从互联网下载的任何内容。
Unsplash提供了可以用于任何目的的免费版权图片,以此来感谢他们的工作。
好的,我已经下载了一张名为Tree.img的图像,将其添加到我们的文档中。
导入请求
从docx。共享导入厘米
# 从Github下载图像
响应 =请求获取(“https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg”)
image =打开(“Tree.jpg”,“wb”)
image写(响应内容)
image.close()
# 添加图像
image_to_add = doc.add_picture("Tree.jpg")
print(f"output \n *** MY Image has width = {image_to_add.width} and Height as - {image_to_add.height}")
输出
*** MY Image has width = 43891200 and Height as - 65836800
4. 我们需要正确缩放图像,因为我的图像太大了。我们可以使用宽度和高度参数。
image_to_add.width = Cm(10)
image_to_add.height = Cm(10)
print(f" *** My New dimensions Image has width = {image_to_add.width} and Height as - {image_to_add.height}")
# 最后保存文档
doc.save('report.docx')
*** My New dimensions Image has width = 3600000 and Height as - 3600000
5. 打开文档,您将看到添加的图像和文本。
6. 将所有内容放在一起。
示例
import requests
from docx.shared import Cm
# 从Github下载图片
response = requests.get("https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg")
image = open("Tree.jpg", "wb")
image.write(response.content)
image.close()
# 添加图片
image_to_add = doc.add_picture("Tree.jpg")
print(f"输出 \n *** 我的图片的宽度为 {image_to_add.width},高度为 {image_to_add.height}")
image_to_add.width = Cm(10)
image_to_add.height = Cm(10)
print(f" *** 我的新尺寸图片的宽度为 {image_to_add.width},高度为 {image_to_add.height}")
# 最后保存文档
doc.save('report.docx')
输出
*** 我的图片的宽度为 43891200,高度为 65836800
*** 我的新尺寸图片的宽度为 3600000,高度为 3600000