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.tables[table_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的自动化数据迁移,可处理数百文档的批量操作。通过扩展解析逻辑,可适配各类文档模板,结合正则表达式等工具还能实现更复杂的内容提取。最终代码已开源在

相关推荐
摸爬滚打李上进39 分钟前
重生学AI第十六集:线性层nn.Linear
人工智能·pytorch·python·神经网络·机器学习
凛铄linshuo2 小时前
爬虫简单实操2——以贴吧为例爬取“某吧”前10页的网页代码
爬虫·python·学习
牛客企业服务2 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
胡斌附体2 小时前
linux测试端口是否可被外部访问
linux·运维·服务器·python·测试·端口测试·临时服务器
likeGhee3 小时前
python缓存装饰器实现方案
开发语言·python·缓存
项目題供诗3 小时前
黑马python(二十五)
开发语言·python
读书点滴3 小时前
笨方法学python -练习14
java·前端·python
笑衬人心。3 小时前
Ubuntu 22.04 修改默认 Python 版本为 Python3 笔记
笔记·python·ubuntu
蛋仔聊测试4 小时前
Playwright 中 Page 对象的常用方法详解
python
前端付豪4 小时前
17、自动化才是正义:用 Python 接管你的日常琐事
后端·python