百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

在 Python 中将 PDF 表格提取为文本、Excel 和 CSV

liuian 2025-02-08 11:50 44 浏览

由于 PDF 文档的复杂性,从 PDF 文件中提取表格数据可能是一项具有挑战性的任务。与简单的文本提取不同,表格需要小心处理,以保留表格结构以及行和列之间的关系。您无需从大量 PDF 表中手动提取数据,而是可以通过编程方式简化和自动化此过程。在本文中,我们将演示如何使

用于将 PDF 表格提取为文本、Excel 和 CSV 的 Python 库

要将 PDF 表中的数据提取为文本、excel 和 CSV 文件,我们可以使用 Spire.PDF for Python 和 Spire.XLS for Python 库。Spire.PDF for Python 主要用于从 PDF 中提取表格数据,Spire.XLS for Python 主要用于将提取的表格数据保存为 Excel 和 CSV 文件。

您可以在项目的终端中运行以下 pip 命令来安装 Spire.PDF for Python 和 Spire.XLS for Python:

pip install Spire.Pdf
pip install Spire.Xls

如果您已经安装了 Spire.PDF for Python 和 Spire.XLS for Python,并且想要升级到最新版本,请使用以下 pip 命令:

pip install --upgrade Spire.Pdf
pip install --upgrade Spire.Xls

在 Python 中将 PDF 表格提取为文本

Spire.PDF for Python 提供的
PdfTableExtractor.ExtractTable(pageIndex: int)
函数允许您访问 PDF 中的表。访问后,您可以使用 PdfTable.GetText(rowIndex: int, columnIndex: int) 函数轻松地从表中检索数据。然后,您可以将检索到的数据保存到文本文件中以供以后使用。

以下示例显示了如何使用 Python 和 Spire.PDF for Python 从 PDF 文件中提取表数据并将结果保存到文本文件中:

from spire.pdf import *
from spire.xls import *

# Define an extract_table_data function to extract table data from PDF
def extract_table_data(pdf_path):
    # Create an instance of the PdfDocument class
    doc = PdfDocument()
    
    try:
        # Load a PDF document
        doc.LoadFromFile(pdf_path)
        # Create a list to store the extracted table data
        table_data = []

        # Create an instance of the PdfTableExtractor class
        extractor = PdfTableExtractor(doc)

        # Iterate through the pages in the PDF document
        for page_index in range(doc.Pages.Count):
            # Get tables within each page
            tables = extractor.ExtractTable(page_index)
            if tables is not None and len(tables) > 0:

                # Iterate through the tables
                for table_index, table in enumerate(tables):
                    row_count = table.GetRowCount()
                    col_count = table.GetColumnCount()

                    table_data.append(f"Table {table_index + 1} of Page {page_index + 1}:\n")

                    # Extract data from each table and append the data to the table_data list
                    for row_index in range(row_count):
                        row_data = []
                        for column_index in range(col_count):
                            data = table.GetText(row_index, column_index)
                            row_data.append(data.strip())
                        table_data.append("  ".join(row_data))

                    table_data.append("\n")

        return table_data

    except Exception as e:
        print(f"Error occurred: {str(e)}")
        return None

# Define a save_table_data_to_text function to save the table data extracted from a PDF to a text file
def save_table_data_to_text(table_data, output_path):
    try:
        with open(output_path, "w", encoding="utf-8") as file:
            file.write("\n".join(table_data))
        print(f"Table data saved to '{output_path}' successfully.")
    except Exception as e:
        print(f"Error occurred while saving table data: {str(e)}")

# Example usage
pdf_path = "Tables.pdf"
output_path = "table_data.txt"

data = extract_table_data(pdf_path)
if data:
    save_table_data_to_text(data, output_path)

使用 Python 从 PDF 中提取表格

在 Python 中将 PDF 表格提取到 Excel

当您需要对表格数据执行进一步的分析、计算或可视化时,将 PDF 表格提取到 Excel 非常有用。通过将 Spire.PDF for Python 与 Spire.XLS for Python 结合使用,您可以轻松地将数据从 PDF 表格导出到 Excel 工作表。

以下示例显示了如何使用 Spire.PDF for Python 和 Spire.XLS for Python 将数据从 PDF 表导出到 Python 中的 Excel 工作表:

from spire.pdf import *
from spire.xls import *

# Define a function to extract data from PDF tables to Excel
def extract_table_data_to_excel(pdf_path, xls_path):
    # Create an instance of the PdfDocument class
    doc = PdfDocument()

    try:
        # Load a PDF document
        doc.LoadFromFile(pdf_path)

        # Create an instance of the PdfTableExtractor class
        extractor = PdfTableExtractor(doc)

        # Create an instance of the Workbook class
        workbook = Workbook()
        # Remove the default 3 worksheets
        workbook.Worksheets.Clear()
        
        # Iterate through the pages in the PDF document
        for page_index in range(doc.Pages.Count):
            # Extract tables from each page
            tables = extractor.ExtractTable(page_index)
            if tables is not None and len(tables) > 0:
                # Iterate through the extracted tables
                for table_index, table in enumerate(tables):
                    # Create a new worksheet for each table
                    worksheet = workbook.CreateEmptySheet()  
                    # Set the worksheet name
                    worksheet.Name = f"Table {table_index + 1} of Page {page_index + 1}"  
                    
                    row_count = table.GetRowCount()
                    col_count = table.GetColumnCount()

                    # Extract data from the table and populate the worksheet
                    for row_index in range(row_count):
                        for column_index in range(col_count):
                            data = table.GetText(row_index, column_index)
                            worksheet.Range[row_index + 1, column_index + 1].Value = data.strip()
                    
                    # Auto adjust column widths of the worksheet
                    worksheet.Range.AutoFitColumns()

        # Save the workbook to the specified Excel file
        workbook.SaveToFile(xls_path, ExcelVersion.Version2013)

    except Exception as e:
        print(f"Error occurred: {str(e)}")

# Example usage
pdf_path = "Tables.pdf"
xls_path = "table_data.xlsx"
extract_table_data_to_excel(pdf_path, xls_path)

使用 Python 将 PDF 表格提取到 Excel

在 Python 中将 PDF 表提取为 CSV

CSV 是一种通用格式,可以通过电子表格软件、数据库、编程语言和数据分析工具打开和处理。将 PDF 表格提取为 CSV 格式使数据易于访问并与各种应用程序和工具兼容。

以下示例显示了如何使用 Spire.PDF for Python 和 Spire.XLS for Python 将数据从 PDF 表导出到 Python 中的 CSV 文件:

from spire.pdf import *
from spire.xls import *

# Define a function to extract data from PDF tables to CSV
def extract_table_data_to_csv(pdf_path, csv_directory):
    # Create an instance of the PdfDocument class
    doc = PdfDocument()

    try:
        # Load a PDF document
        doc.LoadFromFile(pdf_path)

        # Create an instance of the PdfTableExtractor class
        extractor = PdfTableExtractor(doc)

        # Create an instance of the Workbook class
        workbook = Workbook()
        # Remove the default 3 worksheets
        workbook.Worksheets.Clear()
        
        # Iterate through the pages in the PDF document
        for page_index in range(doc.Pages.Count):
            # Extract tables from each page
            tables = extractor.ExtractTable(page_index)
            if tables is not None and len(tables) > 0:
                # Iterate through the extracted tables
                for table_index, table in enumerate(tables):
                    # Create a new worksheet for each table
                    worksheet = workbook.CreateEmptySheet()  
 
                    row_count = table.GetRowCount()
                    col_count = table.GetColumnCount()

                    # Extract data from the table and populate the worksheet
                    for row_index in range(row_count):
                        for column_index in range(col_count):
                            data = table.GetText(row_index, column_index)
                            worksheet.Range[row_index + 1, column_index + 1].Value = data.strip()
                    
                    csv_name = csv_directory + f"Table {table_index + 1} of Page {page_index + 1}" + ".csv"

                    # Save each worksheet to a separate CSV file
                    worksheet.SaveToFile(csv_name, ",", Encoding.get_UTF8())

    except Exception as e:
        print(f"Error occurred: {str(e)}")

# Example usage
pdf_path = "Tables.pdf"
csv_directory = "CSV/"
extract_table_data_to_csv(pdf_path, csv_directory)

使用 Python 将 PDF 表格提取为 CSV

相关推荐

电脑死机咋办(电脑开机蓝屏怎么办)

可按照如下方式重启:1、直接按下“CTRL+ALT+DEL”键,然后选择重启;2、如方式1无效,可按住电源键数秒进行强制关机,然后再次启动即可;3、最后一个办法就是,拔出电池和电源适配器,然后重新安装...

追剧神器免费下载(苹果手机免费追剧软件)

是正规网站茶杯狐官方网站是一款正规的视频播放软件。茶杯狐官方网站拥有各种电影、电视剧、综艺、动漫等视频任由用户们在线自由观看。茶杯狐官方网站所有的视频画质也非常的超清流畅,很安全。茶杯狐软件是很好用的...

平板电脑一键root工具(平板电脑 root)

1、下载APP:ROOT大师;2、打开小米平板USB调试模式;3、安装驱动,提示连接成功4、获取ROOT权限。5、显示更新成功后依次选择:返回-重新启动-系统6、重启后打开桌面的super...

autocad2010激活码怎么获取(cad2010最新激活码密钥免费领取)
  • autocad2010激活码怎么获取(cad2010最新激活码密钥免费领取)
  • autocad2010激活码怎么获取(cad2010最新激活码密钥免费领取)
  • autocad2010激活码怎么获取(cad2010最新激活码密钥免费领取)
  • autocad2010激活码怎么获取(cad2010最新激活码密钥免费领取)
手机u盘驱动器下载(手机u盘驱动器下载安装)

不能直接手机下载到u盘,可以下到手机,然后手机连电脑copy到u盘你只需把你心爱的U盘插到电脑上,然后它会有一个新硬安装向导当它要搜索驱动程序时,你只需将其浏览到你所下载的usb万能驱动文件夹点下...

组装电脑配置价格表(组装电脑顶级配置清单及价格)
  • 组装电脑配置价格表(组装电脑顶级配置清单及价格)
  • 组装电脑配置价格表(组装电脑顶级配置清单及价格)
  • 组装电脑配置价格表(组装电脑顶级配置清单及价格)
  • 组装电脑配置价格表(组装电脑顶级配置清单及价格)
旺旺下载app(旺旺下载链接是多少)

可以下载多换几个下载软件试试直接登录官方appstore里面下载就可以使用了。1、首先在手机中找到appstore。2、点击进入后,在上方的搜索条里输入“阿里旺旺”,选中官方的阿里旺旺。3、点击进...

主机显卡在哪个位置(主机显卡在哪个位置看)

1、集成显卡的位置一般在机箱后面的中部,插口是竖立的。独立显卡的位置一般在机箱后面的下部,插口是横平的。2、独立显卡,一般插在主板中部的插槽,用手可以直接拔出。如果分不清哪个是显卡的插口,就直接看显示...

windows7ultimate下载(windows7 ultimate)

要下载澪Ultimate启动器,您可以按照以下步骤进行操作:1.打开您的网络浏览器,访问澪Ultimate启动器的官方网站或相关下载页面。2.在网站上找到适用于您的操作系统的下载选项。3.点击下...

苹果首次激活时间查询(iphone激活查询官网入口)

登陆苹果官网输入手机的序列号,查看手机的保修日期就可以了,一般保修到期的前一年就是手机的开机激活时间。查看第一次开机激活时间操作方法:1、首先打开设置2、点击通用3、点击关于本机...

u盘启动哪个好用(u盘启动盘哪个最好)

大白菜超级U盘启动盘制作工具,打造你真正的万能U盘!安装后你在U盘里是看到什么文件的,是隐藏分区,这样你放存别的东西时也不会搞乱了。大白菜超级U盘启动盘制作工具,是纯傻瓜式制作U盘启动盘功能的超级万能...

腾达路由器高级设置在哪里(腾达路由器怎么设置安全性高)

方法/步骤分步阅读1/11打开新购的腾达路由器,查看路由器背面的默认IP和管理员密码。小提示:密码为:admin默认管理IP:192.168.0.12/11接好腾达路由器和插上电源通电,等待2-3分钟...

dell新版bios设置恢复(戴尔bios恢复设置)

1)、开机后,在看到DELL图标时,按3下F2,进入BIOS。(灰色界面)2)、分别按键盘上的CapsLock,ScrollLock,以及NumLock三个键,使键盘上相应的三个指示灯点亮。3)、...

重装win7系统需要多少钱(重装一个win7系统要多少钱)

1、win7系统装完后需要占用C盘空间10-15GB,如果把常用软件也安装到C盘,大小超过20+。  2、在分区的时候根据硬盘大小,如果硬盘相对较小,一般建议设置50G,最低不能低于30G。因...

性价比笔记本推荐2025(性价比高的笔记本电脑2021年)

2023年联想推出的一款性价比高的笔记本电脑是联想Yoga7Carbon。它是一款轻薄便携的2合1笔记本,采用了高强度碳纤维材质打造,具有出色的抗撞击性和高端外观。配备了英特尔第11代酷睿处理器、...