简介:本文详细介绍如何使用Python的python-docx库精准识别Word文档中的表格文字,涵盖表格遍历、单元格内容提取、样式处理及异常处理,助力开发者高效处理文档数据。
在办公自动化、数据迁移及文档分析场景中,Word文档中的表格数据常需提取为结构化数据(如CSV、数据库)。传统手动复制效率低下,而python-docx库提供了自动化解决方案。本文聚焦如何通过该库精准识别表格文字,解决开发者在文档解析中的核心痛点。
python-docx库基础与安装python-docx是专门处理Word文档(.docx格式)的Python库,支持段落、表格、样式等元素的读写。其核心优势在于:
通过pip快速安装:
pip install python-docx
建议使用虚拟环境隔离依赖,避免版本冲突。
from docx import Documentdoc = Document("example.docx") # 加载文档for table in doc.tables: # 遍历所有表格for row in table.rows: # 遍历行for cell in row.cells: # 遍历单元格print(cell.text) # 输出单元格文本
关键点:
doc.tables返回文档中所有表格的列表cell.text属性获取纯文本(自动合并段落)单元格可能包含多个段落(如换行符分隔的内容):
for cell in row.cells:paragraphs = cell.paragraphs # 获取单元格内所有段落full_text = "\n".join([p.text for p in paragraphs])print(full_text)
应用场景:解决表格中换行符导致的文本截断问题。
若需保留粗体、颜色等样式,需遍历Run对象:
from docx.shared import RGBColordef get_formatted_text(cell):formatted_text = []for paragraph in cell.paragraphs:for run in paragraph.runs:text = run.textif run.bold:text = f"**{text}**" # 标记粗体if run.font.color.rgb:rgb = run.font.color.rgbtext = f"<span style='color:rgb({rgb[0]},{rgb[1]},{rgb[2]})'>{text}</span>"formatted_text.append(text)return "\n".join(formatted_text)
输出示例:
**标题**<span style='color:rgb(255,0,0)'>重要数据</span>
table = doc.tables[0] # 第一个表格third_row = table.rows[2] # 第三行(索引从0开始)second_col_cell = third_row.cells[1] # 第二列单元格
若表头在第一行,可封装为函数:
def get_header_row(table):return table.rows[0] if table.rows else Noneheader_row = get_header_row(table)if header_row:headers = [cell.text for cell in header_row.cells]print("表头:", headers)
当表格存在合并单元格时,需判断cell.text是否为空:
for row in table.rows:row_data = []for cell in row.cells:if cell.text.strip(): # 非空单元格row_data.append(cell.text)else:# 处理合并单元格逻辑(需结合上下文)row_data.append("合并单元格内容")print(row_data)
建议:结合文档上下文或预定义规则处理合并单元格。
try:doc = Document("example.docx")if not doc.tables:raise ValueError("文档中无表格")# 后续处理...except FileNotFoundError:print("错误:文件未找到")except Exception as e:print(f"解析失败: {str(e)}")
multiprocessing加速
import csvfrom docx import Documentdef docx_table_to_csv(input_path, output_path):doc = Document(input_path)with open(output_path, 'w', newline='', encoding='utf-8') as f:writer = csv.writer(f)for table in doc.tables:# 提取表头(假设第一行为表头)headers = [cell.text.strip() for cell in table.rows[0].cells]writer.writerow(headers)# 提取数据行for row in table.rows[1:]:data = [cell.text.strip() for cell in row.cells]writer.writerow(data)# 使用示例docx_table_to_csv("input.docx", "output.csv")
输出结果:
姓名,年龄,职业张三,30,工程师李四,25,设计师
python-docx不支持直接解析嵌套表格,需递归处理:
def extract_nested_tables(cell):if cell.tables: # 单元格内存在表格for nested_table in cell.tables:for row in nested_table.rows:for nested_cell in row.cells:print(nested_cell.text)else:print(cell.text)
单元格中的制表符\t或换行符\n可能导致解析错误,建议统一替换:
clean_text = cell.text.replace('\t', ' ').replace('\n', ' ')
处理中文文档时,需指定编码:
with open("output.csv", 'w', newline='', encoding='utf-8-sig') as f:# 写入操作...
python-docx通过doc.tables、row.cells等接口实现表格遍历cell.text或paragraphs属性获取pytesseract识别图片表格通过本文的详细指南,开发者可系统掌握python-docx的表格文字识别技术,高效解决文档自动化处理中的核心问题。