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

相关推荐
贤哥哥yyds5 分钟前
GBK转UTF\-8编码自动转换工具 使用文档
python
数量技术宅13 分钟前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
华如锦21 分钟前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai
戴西软件39 分钟前
戴西 DLM 许可授权管理系统:破解无网络环境下工业软件授权难题,助力制造企业降本增效
网络·人工智能·python·深度学习·程序人生·算法·制造
Dxy12393102161 小时前
Python线程锁:为什么多线程会“打架“,以及怎么解决
开发语言·前端·python
小白学大数据1 小时前
线上故障急救:依托 OpenClaw 日志排查 403 和 503 问题
爬虫·python·selenium·数据分析
海兰1 小时前
【web应用】Excel 项目数据自动化分析系统(AI 驱动分析)详细设计与部署指南(附源代码)
前端·人工智能·自动化·excel
databook2 小时前
用SymPy自动因式分解:从面积拼图到代数恒等式
python·数学·动效
艳阳天_.2 小时前
星瀚弹框页面实现
java·前端·python
kernelcraft2 小时前
Boto3:Python 操作 AWS 的官方 SDK
开发语言·python·其他·aws