You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
1.1 KiB
32 lines
1.1 KiB
import win32com.client
|
|
|
|
|
|
def read_word_toc(doc_path):
|
|
# 启动 Word 应用程序
|
|
word = win32com.client.DispatchEx("Word.Application")
|
|
# 设置 Word 为后台运行,不显示窗口
|
|
word.Visible = False
|
|
# 禁用警告弹窗
|
|
word.DisplayAlerts = win32com.client.constants.wdAlertsNone
|
|
|
|
try:
|
|
# 打开 Word 文档
|
|
doc = word.Documents.Open(doc_path)
|
|
# 遍历文档中的所有段落
|
|
for paragraph in doc.Paragraphs:
|
|
# 检查段落样式是否为标题样式
|
|
if paragraph.Style.Name.startswith('Heading'):
|
|
# 打印标题文本和级别
|
|
print(f"Level {paragraph.Style.Name}: {paragraph.Range.Text}")
|
|
except Exception as e:
|
|
print(f"An error occurred: {e}")
|
|
finally:
|
|
# 关闭文档,不保存更改
|
|
doc.Close(SaveChanges=False)
|
|
# 退出 Word 应用程序
|
|
word.Quit()
|
|
|
|
# 替换为你的 Word 文档路径
|
|
doc_path = 'c:/双柏县人口变化及其对教育的影响.docx'
|
|
read_word_toc(doc_path)
|