Python操作Word文档:win32com与docx模块实战指南

云舒
云舒
发布时间:2026-10-13 | 5人浏览过
原创

本文详解Python操作Word文档的两种主流方式。首先介绍基于Windows平台的win32com模块,通过COM接口调用Word应用程序实现段落遍历与内容读取;其次讲解跨平台的python-docx库,涵盖环境安装、文档创建、表格生成及数据读取等核心功能。内容包含完整代码示例与官方文档链接,适用于不同操作系统下的自动化办公需求。

本文实例总结了Python中操作Word文档的常见方法,旨在为读者提供实用的参考代码与技巧。

主要介绍以下两种实现路径:

  • 方法一:使用win32com模块
  • 方法二:使用docx模块

1. 基于win32com扩展包的操作

该方式仅适用于Windows操作系统平台。

具体实现代码如下:

# coding=utf-8
import win32com
from win32com.client import Dispatch, DispatchEx
word = Dispatch('Word.Application') # 打开word应用程序
# word = DispatchEx('Word.Application') #启动独立的进程
word.Visible = 0 # 后台运行,不显示
word.DisplayAlerts = 0 # 不警告
path = 'G:/WorkSpace/Python/tmp/test.docx' # word文件路径
doc = word.Documents.Open(FileName=path, Encoding='gbk')
# content = doc.Range(doc.Content.Start, doc.Content.End)
# content = doc.Range()
print '----------------'
print '段落数: ', doc.Paragraphs.count
# 利用下标遍历段落
for i in range(len(doc.Paragraphs)):
  para = doc.Paragraphs[i]
  print para.Range.text
print '-------------------------'
# 直接遍历段落
for para in doc.paragraphs:
  print para.Range.text
  # print para #只能用于文档内容全英文的情况
doc.Close() # 关闭word文档
# word.Quit #关闭word程序

2. 基于docx扩展包的操作

其核心优势在于不依赖特定操作系统,具备良好的跨平台兼容性。

安装步骤如下:

pip install python-docx

详细参考文档地址:https://python-docx.readthedocs.io/en/latest/index.html

基础代码示例如下:

import docx
def read_docx(file_name):
  doc = docx.Document(file_name)
  content = '\n'.join([para.text for para in doc.paragraphs])
  return content

创建表格的操作示例

# coding=utf-8
import docx
doc = docx.Document()
table = doc.add_table(rows=1, cols=3, style='Table Grid') #创建带边框的表格
hdr_cells = table.rows[0].cells # 获取第0行所有所有单元格
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
# 添加三行数据
data_lines = 3
for i in range(data_lines):
  cells = table.add_row().cells
  cells[0].text = 'Name%s' % i
  cells[1].text = 'Id%s' % i
  cells[2].text = 'Desc%s' % i
rows = 2
cols = 4
table = doc.add_table(rows=rows, cols=cols)
val = 1
for i in range(rows):
  cells = table.rows[i].cells
  for j in range(cols):
    cells[j].text = str(val * 10)
    val += 1
doc.save('tmp.docx')

读取表格内容的操作示例

# coding=utf-8
import docx
doc = docx.Document('tmp.docx')
for table in doc.tables: # 遍历所有表格
  print '----table------'
  for row in table.rows: # 遍历表格的所有行
    # row_str = '\t'.join([cell.text for cell in row.cells]) # 一行数据
    # print row_str
    for cell in row.cells:
      print cell.text, '\t',
    print

关于样式设置的更多参考信息,请访问:https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html

如需进一步了解Python相关知识,建议查阅本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。

希望本文提供的代码示例与说明能对您的Python程序设计工作有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表