链接
概述
关于python-docx这个库,没有添加目录的内容,也没有添加页码的内容;通过查找,发现win32com这个库可以解决这些问题。
解决目录问题
我是通过win32com这个库写了一个更新插入目录页码的方法,先运行你使用python-docx模块所写的生成word文档的方法,将生成的word文档的路径写入下面代码,运行之后,就会生成有目录有页码的word文档了
# -*- coding: utf-8 -*-
import os
import win32com.client
from win32com.client import constants
#更新目录
def update_toc(docx_file):
word = win32com.client.DispatchEx("Word.Application")
word.Visible = 0 # 设置应用可见
word.DisplayAlerts = 0
doc = word.Documents.Open(docx_file)
wd_section = doc.Sections(1) # 注意section内部成员编号是从1开始的
wd_section.Footers(constants.wdHeaderFooterPrimary).PageNumbers.Add(
PageNumberAlignment=constants.wdAlignPageNumberCenter) # 添加页码
toc_count = doc.TablesOfContents.Count
if toc_count == 0:
#
for i, p in enumerate(doc.Paragraphs):
if '目录' in p.Range.Text:
try:
p.Range.InsertParagraphAfter()
# p.Range.InsertAfter("---")
# print(doc.Paragraphs(i+2))
parag_range = doc.Paragraphs(i+2).Range
parag_range.Font.Name = '黑体'
parag_range.Font.Size = 14
parag_range.Font.Bold = constants.wdToggle
parag_range.Font.Bold = constants.wdToggle
parag_range.Font.Size = 12
doc.TablesOfContents.Add(Range=parag_range,
UseHeadingStyles=True,
LowerHeadingLevel=3)
except Exception as e:
print("报错:", e, "报错")
break
elif toc_count == 1:
toc = doc.TablesOfContents(1)
toc.Update()
print('TOC should have been updated.')
else:
print('TOC has not been updated for sure...')
doc.Close(SaveChanges=True)
word.Quit()
if __name__=='__main__':
docx_file = "D:\文档\word/报告.docx" #python-docx生成的word文档路径
update_toc(docx_file)