四时宝库

程序员的知识宝库

python将PDF格式文档转换为excel文档

首先 安装pdfplumber库

pip install pdfplumber openpyxl

然后转换

#导入两个模块
import pdfplumber  
import pandas as pd   
  
# 初始化DataFrame数据对象、用于DataFrame数据保存  
data_frame = pd.DataFrame()  
  
# pdf 文件路径  
pdf_file = r'C:\Users\Lenovo\Downloads\Documents\2023年国家社科基金年度项目立项名单.pdf'  
  
# 读取pdf数据  
with pdfplumber.open(pdf_file) as pdf_data:  
    for page in pdf_data.pages:  
        # 每一页的Tbale表格数据  
        table = page.extract_table()  
        if table:  # 确保table不为空  
            # 将每一页的数据写入一个DataFrame对象  
            data_frame_page = pd.DataFrame(table[1:], columns=table[0])  
            # 合并每一页的表格数据(在循环外部进行)  
            data_frame = pd.concat([data_frame, data_frame_page], ignore_index=True)  
# 简单的数据清洗、删除其中列值全部为Nan的数据列  
data_frame.dropna(axis=1, how='all', inplace=True)  
  
# 保存EXCEL表格  
# excel 文件路径  
excel_path = r'C:\Users\Lenovo\Downloads\Documents\2023年国家社科基金年度项目立项名单.xlsx'  
  
# DataFrame数据保存到Excel数据表中  
data_frame.to_excel(excel_path, index=False)

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接