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

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

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

由于 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.重新启动电脑或手机,并检查是否仍然没有百度应用或网站。2.使用其他搜索引擎搜索“百度官网”或“百度下载”,下载安装百度应用或访问百度官网。3.检...

account(account怎么读)

Account是英语中的一个单词,它的意思是账户或账目。这个词在商业交易和财务管理中非常常见,通常用于记录和追踪资金的流动和使用情况。此外,在计算机领域中,Account也可以指代用户账户或电子邮箱账...

住房公积金怎么取出来(异地的住房公积金怎么取出来)

1、职工达到法定退休、离休年龄且办理手续后,提供相关有效证明材料,包含证书或文件复印件等前往相关部门申请;2、职工去世后,其亲属提供死亡证明、单位出具的继承人证明、领取人的身份证复印件和支取申请书即可...

26键盘拼音打字口诀(手机26键打字训练)

试答:用口诀法记忆汉语拼音知识(1)见到a母莫放过,没有a母找o、e,i、u并列标在后,i上标调把点抹。(2)i、in、ing前无声母,加个y母来弥补。(3)ü见j、q、x,两点定要抹,ü拼...

2025年qq最新版本下载(2021qq最新版本下载)

目前来看的话java版的QQ还是可以用的。.我们需要用那种比较老式的塞班系统手机才能下载安装使用,就目前的时代使用它的意义就看我们自己怎么理解了,不过社会在进步,科技也在发展,要想更强时代的潮流,万物...

cellular版是什么意思(cellular是啥)

  ipad又出了一个cellular版,很多果粉不知道cellular版是什么意思,在购买ipad时也不知道是cellular版好还是wifi版好,要想知道哪一款好得首先了解两个版本的区别。  c...

如何删除ie缓存文件(清楚ie缓存)

1.可以通过清理IE浏览器缓存来解决问题。2.IE浏览器在访问网页时会自动缓存一些网页数据,这样可以提高网页访问速度,但也会占用一定的磁盘空间。如果缓存过多,可能会导致浏览器运行缓慢或出现其他问题...

华为 官翻机(什么是华为官翻机)

华为官翻机指的是华为公司推出的官方翻新手机。官翻机是指经过华为官方认证的二手手机,在严格的检测和修复后重新销售。它们经过了一系列的测试和维修,确保其性能和品质符合华为的标准,并提供一定的保修服务。华为...

应用软件开发(应用软件开发流程)

“人工智能技术应用”,这个词我们多少会了解一点,但是像这种比较高大上的词,我们总是比较模糊,没有准确的概念,总感觉就是那么一回事,那接下来就给大家简单说明一下。人工智能技术应用是属于普通高等学校本科专...

超快精简xp(xp精简软件)

没有具体介绍,可以参考以下XP简化版是一种简化的软件开发方法,旨在提高生产力、降低成本和改进产品质量。其核心原则包括小规模团队、频繁交付、持续集成和测试驱动开发。通过这些原则,XP简化版鼓励开发团队更...

台式机不用无线网卡连wifi(台式机不用无线网卡如何无线上网)

电脑没有无线网卡是无法直接连wifi无线网络的,但是可以使用USB外置无线网卡连接。电脑连接WiFi无线网络是需要有无线网卡的硬件设备才可以正常使用的。如果电脑主板是没有无线网卡硬件配置的可以使用US...

w10系统启动盘u盘(win10系统u盘启动盘)

U盘装系统步骤:1.制作U盘启动盘。这里推荐大白菜U盘启动盘制作工具,在网上一搜便是。2.U盘启动盘做好了,我们还需要一个GHOST文件,可以从网上下载一个ghost版的XP/WIN7/WIN8系统,...

百度网盘旧版本下载(百度网盘旧版本下载方法)

百度网盘文件怎的么下载,方法/步骤分步阅读1/5选中文件进入百度网盘的文件页面,勾选想要下载的文件。2/5点击下载在左下角,点击下载的按钮。3/5点击下载管理在右上角,点击下载管理的图标。4/5点击设...

金山手机卫士安卓版(金山手机卫士官方网站)

您好,进入金山手机卫士软件管理功能里可以在里面点击软件然后进行设置即可。不敢说很准,高查杀率的同时必然会产生高误杀的可能。我最近试用了有些天了,感觉蛮好的,刚装那天帮我扫了个木马出来。今天我同学,刚中...

u盘无法格式化此卷受写保护(u盘无法格式化,此卷受写保护)

方法如下:1、一般的逻辑坏道很好解决,在U盘盘符的上方点击右键,在弹出的窗口中点击属性。2、在打开的属性窗口上部点击工具选项卡,然后在工具选项卡中点击检查。3、在弹出的对话框中点击扫描并修复驱动器,待...