目录
-
- 专栏导读
- 环境准备
- 核心库介绍
- 单个Word文档表格提取
-
- 批量处理多个Word文档
-
- 高级功能
-
- 完整示例:智能批量提取
- 注意事项
- 总结
专栏导读
-
欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
-
️ 博客主页:请点击——> 一晌小贪欢的博客主页求关注
-
该系列文章专栏:请点击——>Python办公自动化专栏求订阅
-
此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅
-
此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
-
文章作者技术和水平有限,如果文中出现错误,希望大家能指正
-
❤️ 欢迎各位佬关注! ❤️
在日常办公中,我们经常需要从大量的Word文档中提取表格数据进行分析和处理。手动复制粘贴不仅效率低下,还容易出错。本文将介绍如何使用Python自动化批量提取Word文档中的表格数据。
环境准备
pip install python-docx
pip install pandas
pip install openpyxl
核心库介绍
- python-docx:用于读取和操作Word文档
- pandas:用于数据处理和分析
- openpyxl:用于Excel文件的读写操作
单个Word文档表格提取
基础提取方法
from docx import Document
import pandas as pd
def extract_tables_from_word(file_path):
"""
从Word文档中提取所有表格
Args:
file_path (str): Word文档路径
Returns:
list: 包含所有表格数据的列表
"""
doc = Document(file_path)
tables_data = []
for i, table in enumerate(doc.tables):
table_data = []
for row in table.rows:
row_data = []
for cell in row.cells:
row_data.append(cell.text.strip())
table_data.append(row_data)
tables_data.append({
'table_index': i + 1,
'data': table_data
})
return tables_data
file_path = "example.docx"
tables = extract_tables_from_word(file_path)
for table_info in tables:
print(f"表格 {
table_info['table_index']}:")
for row in table_info['data']:
print(row)
print("-" * 50)
转换为DataFrame
def table_to_dataframe(table_data, has_header=True):
"""
将表格数据转换为pandas DataFrame
Args:
table_data (list): 表格数据
has_header (bool): 是否包含表头
Returns:
pd.DataFrame: 转换后的DataFrame
"""
if not table_data:
return pd.DataFrame()
if has_header:
df = pd.DataFrame(table_data[1:], columns=table_data[0])
else:
df = pd.DataFrame(table_data)
return df
for table_info in tables:
df = table_to_dataframe(table_info['data'])
print(f"表格 {
table_info['table_index']} DataFrame:")
print(df)
print("\n")
批量处理多个Word文档
批量提取并保存到Excel
import os
from pathlib import Path
def batch_extract_word_tables(folder_path, output_file="extracted_tables.xlsx"):
"""
批量提取文件夹中所有Word文档的表格
Args:
folder_path (str): 包含Word文档的文件夹路径
output_file (str): 输出Excel文件名
"""
folder = Path(folder_path)
all_tables = {
}
for file_path in folder.glob("*.docx"):
if file_path.name.startswith("~$"):
continue
print(f"正在处理: {
file_path.name}")
try:
tables = extract_tables_from_word(file_path)
for table_info in tables:
table_key = f"{
file_path.stem}_表格{
table_info['table_index']}"
df = table_to_dataframe(table_info