0 tools

1
2
pip install python-docx
pip install pywin32

python-docx是一个比较好用的处理Word的工具库,参考python-docx 0.8.11 文档

此外,由于python-docx只支持.docx,对于.doc需要使用pywin32库进行格式转换,参考Python for Windows (pywin32)

1 pywin32

Microsoft Word 97-2003的旧版本文件名后缀是 .doc,2007版以上后缀名是 .docx

要把旧版本的.doc转换成.docx,手动操作用Office Word打开原文件另存为.docx文件即可。

要批量处理,则可以使用pywin32调用API自动完成上述过程。

pywin32 是一个扩展模块, 封装了几乎所有的 Windows API ,例如调用 Office 等应用组件、删除指定文件、获取鼠标坐标等等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from win32com import client as wc # 引入模块
import os

def doc2docx(path):
path_list = os.listdir(path) # 获取路径下的所有文件
doc_list = [os.path.join(path,str(i)) for i in path_list if str(i).endswith('doc')] # 筛选.doc文件
word = wc.Dispatch('Word.Application') # 启动office word 应用程序
print(doc_list)
for path in doc_list: # 逐个转换
print(path)
doc = word.Documents.Open(path) # 使用word打开该文件
save_path = str(path).replace('doc','docx') # 修改后缀名
doc.SaveAs(save_path, 12) # 参数12代表另存为docx
doc.Close() # 关闭该文件
# os.remove(path) # 删除原文件
print('{} Save sucessfully '.format(save_path))
word.Quit() # 关闭Word

SaveAs() 方法的相关参数可参考 Document.SaveAs2 方法 (Word) | Microsoft Docs

2 python-docx

2.1 基本结构

python-docxDocument对象代表一个.docx文档,其基本结构如下:

image-20211221171806438

2.2 常用操作
  • 创建空白文档对象
1
2
3
4
5
from docx import Document
document = Document()
p = document.add_paragraph('A new paragraph') # 增加一个段落
path = r'D:\new.docx' # 设置保存路径和文件名
document.save(path) # 保存文档

image-20211221180443662

  • 从原文件创建文档对象
1
2
3
from docx import Document
path = r'D:\test.docx'Python
document = Document(path)

image-20211221180936170

  • 读取段落并输出
1
2
for p in document.paragraphs:
print(p.text)

image-20211229172518790

  • 读取表格并输出

需要注意的是,合并的单元格会被拆分并且对内容进行自动填充,所以会有重复内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for table in document.tables:
i = 1
for row in table.rows:
print('第%d行:'%i, end=" ")
i += 1
for cell in row.cells:
print(cell.text, end=" ")
print()
print('#'*64)
j = 1
for col in table.columns:
print('第%d列:'%j, end=" ")
j += 1
for cell in col.cells:
print(cell.text, end=" ")
print()
print('#'*64)

image-20211229174415906

  • 多个表格格式化,用矩阵存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def getTables(doc):  # 获取doc中的表格,以矩阵形式返回
tables = []
for table in doc.tables:
tb = []
for row in table.rows:
t_row = []
for cell in row.cells:
t_row.append(cell.text.replace(' ', ''))
tb.append(t_row)
tables.append(tb)
return tables


def printTable(table):
print('[')
for row in table:
print(row)
print(']')


t_cnt = 0
for table in getTables(document):
t_cnt += 1
print('表%d:'%t_cnt)
printTable(table)

image-20211229175831809