from docx import Documentfrom openpyxl import Workbookfrom openpyxl.styles import Alignment, Border, borders, colors,Side# 原始word文件和要生成的Excel文件fn_word = 'E:\\Desktop\\提取章节标题.docx'fn_excel = fn_word[:-5] + '2.xlsx'# 创建空白Excel文件,获取第一个空白工作表wb = Workbook()ws = wb.worksheets[0]# 添加表头ws.append(['一级目录','二级目录','三级目录'])first2,first3 = 1,1# 遍历word文件中的所有段落文本for p in Document(fn_word).paragraphs:# 删除段落文本两侧的空白字符txt = p.text.rstrip()# 直接跳过空行if not txt:continue# 添加为一级标题if p.style.name == 'Heading 1':first2 = 1print(p.text)ws.append([txt,'',''])# 添加为二级标题elif p.style.name == 'Heading 2':print(p.text)if first2==1:# 第一个二级目录,不添加新行# 直接和一级目录写在同一行#print(txt)list(ws.rows)[-1][1].value = txtfirst2 = first2 + 1elif first2>1:# 新增一行添加为二级标题#print(txt)ws.append(['',txt,''])first3 = 1# 添加为三级标题elif p.style.name == 'Heading 3':print(p.text)if first3==1:# 第一个三级目录,不添加新行,直接写和二级在同一行#print(txt)list(ws.rows)[-1][2].value = txtfirst3 = first3 + 1elif first3>1:# 新增一行添加为三级目录print(txt)ws.append(['','',txt])wb.save(fn_excel)# 设置单元格边框side = Side(border_style=borders.BORDER_THICK,color=colors.BLACK)for row in ws.rows:for cell in row:cell.border = Border(top=side, bottom=side,left=side, right=side)start1, start2 = 1, 1for index, row in enumerate(ws.rows, start=1):# 合并第一列的指定单元格,水平左对齐,垂直居中对齐if row[0].value:if index > start1:ws.merge_cells(f'A{start1}:A{index-1}')ws[f'A{start1}'].alignment = Alignment(horizontal='left',vertical='center')start1 = index# 合并第二列的指定单元格,水平左对齐,垂直居中对齐if row[1].value:if index > start2:ws.merge_cells(f'B{start2}:B{index-1}')ws[f'B{start2}'].alignment = Alignment(horizontal='left',vertical='center')start2 = indexif index > start1:ws.merge_cells(f'A{start1}:A{index}')ws[f'A{start1}'].alignment = Alignment(horizontal='left',vertical='center')if index > start2:ws.merge_cells(f'B{start2}:B{index}')ws[f'B{start2}'].alignment = Alignment(horizontal='left',vertical='center')wb.save(fn_excel)
效果图
获取结果
项目场景:
Python提取Word文件中的目录标题保存为Excel文件,本代码以获取三级标题为例
问题描述:
python3安装docx模块出现Import Error: No module named 'exceptions'
卸载不兼容的docx,直接安装python-docx如果pipinstalldocx过请先卸载,输入如下指令: pipuninstalldocx方法一: pipinstall python-docx
提示:pip 是 Python 包管理工具,该工具提供了对Python 包的查找、下载、安装、卸载的功能,是在直接在cmd中运行的,不需要进入到python中运行
学习引用:
利用python批量处理Word文件——正文、标题
/xtfge0915/article/details/83479922