Python - 使用 .docx 模块

pythonserver side programmingprogramming

Word 文档包含包装在三个对象级别内的格式化文本。最低级别 - 运行对象、中间级别 - 段落对象和最高级别 - 文档对象。

因此,我们无法使用普通文本编辑器处理这些文档。但我们可以使用 python-docx 模块在 python 中操作这些 word 文档。

  • 第一步是安装此第三方模块 python-docx。您可以使用 pip “pip install python-docx”
  • 安装后导入 “docx” 而不是 “python-docx”。
  • 使用 “docx.Document”类开始使用 word 文档。

示例

# import docx NOT python-docx
import docx
# 创建 word 文档实例
doc = docx.Document()
# 添加 0 级标题(最大标题)
doc.add_heading('Heading for the document', 0)
# 添加段落并存储
# 对象在变量中
doc_para = doc.add_paragraph('Your paragraph goes here, ')
# 添加运行,即样式,如
# 粗体、斜体、下划线等。
doc_para.add_run('hey there, bold here').bold = True
doc_para.add_run(', and ')
doc_para.add_run('these words are italic').italic = True
# 添加分页符以开始新页面
doc.add_page_break()
# 添加 2 级标题
doc.add_heading('Heading level 2', 2)
# 还可以将图片添加到我们的 word 文档中
# 宽度是可选的
doc.add_picture('path_to_picture')
# 现在将文档保存到某个位置
doc.save('path_to_document')

相关文章