python3 获取某个文件夹所有的pdf文件表格提取表格并一起合并到excel文件

下面是一个完整的示例,其中包括了merge_tables_to_excel函数的定义,并且假设该函数的功能是从每个PDF文件中提取第一个表格并将其合并到一个Excel文件中:

python 复制代码
import os  
from pathlib import Path  
import pandas as pd  
import pdfplumber  
  
def extract_first_table_from_pdf(pdf_path):  
    try:  
        with pdfplumber.open(pdf_path) as pdf:  
            for page in pdf.pages:  
                tables = page.extract_tables()  
                if tables:  
                # tables[0]   pdf中的第一个表格,如果pdf有第二个表格你可以修改为tables[1] 根据你需求来调整
                    return tables[0]   
    except Exception as e:  
        print(f"Error reading {pdf_path}: {e}")  
        return None  
  
def merge_tables_to_excel(pdf_files, excel_path):  
    all_tables = []  
    for pdf_path in pdf_files:  
        first_table = extract_first_table_from_pdf(pdf_path)  
        if first_table:  
            df_table = pd.DataFrame(first_table[1:], columns=first_table[0])  
            all_tables.append(df_table)  
      
    if all_tables:  
        merged_tables_df = pd.concat(all_tables, ignore_index=True)  
        merged_tables_df.to_excel(excel_path, sheet_name='Merged Tables', index=False)  
        print(f"Tables have been saved to {excel_path}")  
    else:  
        print("No tables found in the PDF files.")  
  
def find_all_pdf_files(directory):  
    return list(Path(directory).glob("*.pdf"))  
  
if __name__ == "__main__":  
    # 指定PDF文件夹路径  
    pdf_folder = Path("refer")  
    # 获取文件夹中所有的PDF文件  
    pdf_files = find_all_pdf_files(pdf_folder)  
      
    # 打印找到的PDF文件列表  
    print("Found PDF files:", [str(file) for file in pdf_files])  
      
    # 指定要保存的Excel文件路径  
    excel_path = "merged_tables.xlsx"  
      
    # 提取并合并表格数据到Excel文件  
    merge_tables_to_excel(pdf_files, excel_path)

运行结果如图所示:

如果你想要遍历一个文件夹中的所有子文件夹,并获取每个子文件夹中的PDF文件,你可以使用递归函数来实现这个功能。下面是一个修改后的代码示例,它会递归地搜索指定目录及其所有子目录中的PDF文件:

python 复制代码
import os  
from pathlib import Path  
  
def find_all_pdf_files(directory):  
    pdf_files = []  
    for root, dirs, files in os.walk(directory):  
        for file in files:  
            if file.lower().endswith('.pdf'):  
                pdf_files.append(Path(root) / file)  
    return pdf_files  
  
if __name__ == "__main__":  
    # 指定PDF文件夹路径  
    pdf_folder = Path("refer")  
      
    # 获取文件夹中所有的PDF文件,包括子文件夹中的PDF文件  
    pdf_files = find_all_pdf_files(pdf_folder)  
      
    # 打印找到的PDF文件列表  
    print("Found PDF files:", [str(file) for file in pdf_files])  
      
    # 指定要保存的Excel文件路径  
    excel_path = "merged_tables.xlsx"  
      
    # 提取并合并表格数据到Excel文件  
    merge_tables_to_excel(pdf_files, excel_path)

在这个示例中,find_all_pdf_files 函数使用 os.walk() 来递归遍历目录和子目录。os.walk() 会为每个目录返回一个三元组,包含当前目录的路径、当前目录下的子目录名列表,以及当前目录下的文件名列表。函数遍历每个文件名,检查它是否以 .pdf 结尾(不区分大小写),如果是,则将其添加到 pdf_files 列表中。

请确保你的 merge_tables_to_excel 函数能够处理多个PDF文件中的表格合并到Excel文件的逻辑。如果你需要更具体的帮助来定义这个函数,请提供更多关于你希望如何合并表格的信息。

相关推荐
52Hz1181 小时前
力扣73.矩阵置零、54.螺旋矩阵、48.旋转图像
python·算法·leetcode·矩阵
weixin_462446232 小时前
Python 使用 openpyxl 从 URL 读取 Excel 并获取 Sheet 及单元格样式信息
python·excel·openpyxl
毕设源码-钟学长2 小时前
【开题答辩全过程】以 基于Python的健康食谱规划系统的设计与实现为例,包含答辩的问题和答案
开发语言·python
wtsolutions3 小时前
MCP Server Integration - JSON to Excel for AI and Automation
json·excel
百***78753 小时前
Grok-4.1技术深度解析:双版本架构突破与Python API快速集成指南
大数据·python·架构
2501_942191774 小时前
基于YOLO11-HSFPN的数字检测与识别模型实现详解
python
开开心心就好4 小时前
音频编辑工具,多端支持基础剪辑易操作
java·网络·windows·java-ee·电脑·maven·excel
忧郁的橙子.5 小时前
26期_01_Pyhton基本语法
python
sunfove5 小时前
实战篇:用 Python 徒手实现模拟退火算法解决 TSP 问题
开发语言·python·模拟退火算法
我是菜鸟0713号6 小时前
Qt + Python 算法集成的一种低耦合实践:FastAPI 服务化方案
python·qt·fastapi