python批量解析提取word内容到excel

基于Python实现Word文档内容批量提取与Excel自动化存储

引言

在日常办公场景中,常需要从大量Word文档中提取结构化数据并整理到Excel表格中。传统手动操作效率低下,本文介绍如何通过Python实现自动化批处理,使用python-docx和openpyxl库完成以下功能:

  1. 批量读取指定目录下的Word文档

  2. 解析文档中的文本、表格等内容

  3. 按规则存储到Excel文件

  4. 实现高效准确的数据迁移


一、环境准备

1.1 安装依赖库

```bash

pip install python-docx openpyxl pandas

```

1.2 库说明

  • **python-docx**: 读写Word文档

  • **openpyxl**: 操作Excel文件

  • **pandas**: 数据整理与导出


二、实现步骤

2.1 创建基础框架

```python

import os

from docx import Document

import pandas as pd

def process_word_files(input_dir, output_file):

data = \[\]

for filename in os.listdir(input_dir):

if filename.endswith('.docx'):

filepath = os.path.join(input_dir, filename)

doc_data = parse_word(filepath)

data.append(doc_data)

save_to_excel(data, output_file)

def parse_word(filepath):

解析逻辑

pass

def save_to_excel(data, output_file):

存储逻辑

pass

```

2.2 文档解析函数实现

```python

def parse_word(filepath):

doc = Document(filepath)

result = {

'filename': os.path.basename(filepath),

'paragraphs': \[\],

'tables': \[\]

}

提取段落文本

for para in doc.paragraphs:

if para.text.strip():

result'paragraphs'.append(para.text)

提取表格数据

for table in doc.tables:

table_data = \[\]

for row in table.rows:

row_data = cell.text for cell in row.cells

table_data.append(row_data)

result'tables'.append(table_data)

return result

```

2.3 Excel存储函数优化

```python

def save_to_excel(data, output_file):

excel_data = \[\]

for item in data:

处理段落数据

para_str = '\n'.join(item'paragraphs')

处理表格数据

table_str = ''

for i, table in enumerate(item'tables', 1):

table_str += f'Table {i}:\n'

table_str += '\n'.join(' \| '.join(row) for row in table)

table_str += '\n\n'

excel_data.append({

'文件名': item'filename',

'正文内容': para_str,

'表格内容': table_str.strip()

})

df = pd.DataFrame(excel_data)

df.to_excel(output_file, index=False)

```


三、高级处理技巧

3.1 结构化数据提取

```python

示例:提取带特定样式的文本

def extract_special_paragraphs(doc):

special_texts = \[\]

for para in doc.paragraphs:

if para.style.name.startswith('Heading'):

special_texts.append({

'style': para.style.name,

'text': para.text

})

return special_texts

```

3.2 表格数据精准定位

```python

def extract_specific_table(doc, table_index=0):

try:

table = doc.tablestable_index

return \[cell.text for cell in row.cells for row in table.rows]

except IndexError:

return \[\]

```

3.3 批量处理增强

```python

多线程处理加速

from concurrent.futures import ThreadPoolExecutor

def batch_process(files):

with ThreadPoolExecutor() as executor:

results = list(executor.map(parse_word, files))

return results

```


四、执行与测试

```python

if name == 'main':

input_folder = './documents'

output_file = './output.xlsx'

process_word_files(input_folder, output_file)

```


五、注意事项

  1. 文件编码统一保存为UTF-8

  2. 处理复杂表格时建议添加边界检查

  3. 使用try-except块处理异常文档

  4. 大数据量时建议分批次写入Excel


结论

本方案实现了从Word到Excel的自动化数据迁移,可处理数百文档的批量操作。通过扩展解析逻辑,可适配各类文档模板,结合正则表达式等工具还能实现更复杂的内容提取。最终代码已开源在

相关推荐
你好潘先生14 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师14 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码14 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf14 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB2 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码3 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python