目录
  • 需求
    • 一、实现效果图
    • 二、pdfplumber 库
    • 三、代码实现
      • 1、导入相关包
      • 2、读取 pdf , 并获取 pdf 的页数
      • 3、提取单个 pdf 文件,保存成 excel
      • 4、提取文件夹下多个 pdf 文件,保存成 excel
  • 小结

    需求

    想要提取 pdf 的数据,保存到 excel 中。虽然是可以直接利用 WPS 将 pdf 文件输出成 excel,但这个功能是收费的,而且如果将大量pdf转excel的时候,手动去输出是非常耗时的。我们可以利用 python 的三方工具库 pdfplumber 快速完成这个功能。

    一、实现效果图

    python pdfplumber库批量提取pdf表格数据转换为excel

    二、pdfplumber 库

    pdfplumber 是一个开源 python 工具库-,可以方便地获取 pdf 的各种信息,包括文本、表格、图表、尺寸等。完成我们本文的需求,主要使用 pdfplumber 提取 pdf 表格数据。

    安装命令

    pip install pdfplumber
    

    三、代码实现

    1、导入相关包

    import pdfplumber
    import pandas as pd
    

    2、读取 pdf , 并获取 pdf 的页数

    pdf = pdfplumber.open("/Users/wangwangyuqing/Desktop/1.pdf")
    pages = pdf.pages
    

    3、提取单个 pdf 文件,保存成 excel

    if len(pages) > 1:
        tables = []
        for each in pages:
            table = each.extract_table()
            tables.extend(table)
    else:
        tables = each.extract_table()
    data = pd.DataFrame(tables[1:], columns=tables[0])
    data
    data.to_excel("/Users/wangwangyuqing/Desktop/1.xlsx", index=False)
    

    4、提取文件夹下多个 pdf 文件,保存成 excel

    import os
    import glob
    path = r'/Users/wangwangyuqing/Desktop/pdf文件'
    for f in glob.glob(os.path.join(path, "*.pdf")):
        res = save_pdf_to_excel(f)
        print(res)
    def save_pdf_to_excel(path):
        #     print('文件名为:',path.split('/')[-1].split('.')[0] + '.xlsx')
        pdf = pdfplumber.open(path)
        pages = pdf.pages
        if len(pages) > 1:
            tables = []
            for each in pages:
                table = each.extract_table()
                tables.extend(table)
        else:
            tables = each.extract_table()
        data = pd.DataFrame(tables[1:], columns=tables[0])
        file_name = path.split('/')[-1].split('.')[0] + '.xlsx'
        data.to_excel("/Users/wangwangyuqing/Desktop/data/{}".format(file_name), index=False)
        return '保存成功!'
    

    小结

    python 中还有很多库可以处理 pdf,比如 PyPDF2、pdfminer 等,本文选择pdfplumber 的原因在于能轻松访问有关 PDF 的所有详细信息,包括作者、来源、日期等,并且用于提取文本和表格的方法灵活可定制。大家可以根据手头数据需求,再去解锁 pdfplumber 的更多用法。

    以上就是python pdfplumber库批量提取pdf表格数据转换为excel的详细内容,更多关于python pdfplumber库pdf转换excel的资料请关注其它相关文章!

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。