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

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

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

由于 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

相关推荐

RazorSQL Mac版(SQL数据库查询工具)

RazorSQLMac特别版是一款看似简单实则功能非常出色的SQL数据库查询、编辑、浏览和管理工具。RazorSQLformac特别版可以帮你管理多个数据库,支持主流的30多种数据库,包括Ca...

史上最强!开源数据库管理工具DBeaver 24.2发布

DBeaverCommunity是一个免费的跨平台数据库工具,面向开发人员、数据库管理员、分析师和所有使用数据的人员。它支持所有流行的SQL数据库,如MySQL、MariaDB、PostgreSQL...

10个优秀的MySQL管理工具,都是大佬们的珍藏

Mysql开源、体积小、速度快、成本低、安全性高,目前在全球中小型网站中被广泛应用。今天给大家介绍10个优秀的MySQL管理工具,都是大佬们的珍藏,对你有用的话,可以收藏转发。1、Induction...

Mac电脑如何安装向量数据库Milvus

Milvus是一个高性能、高度可扩展的矢量数据库,可在从笔记本电脑到大规模分布式系统的各种环境中高效运行。Milvus提供强大的数据建模功能,使您能够将非结构化或多模态数据组织成结构化集合。Mil...

干掉 PowerDesigner!这款国人开源的数据库设计工具真香

当我们在项目开发初期时,往往需要设计大量的表,此时使用数据库设计工具就会比较高效!今天给大家推荐一款国人开源的数据库设计工具chiner,界面漂亮,功能强大,希望对大家有所帮助!聊聊PowerDesi...

数据库管理工具推荐!SQL Studio:免费、高效,歪...

随着国际环境的变化,越来越多的企业基于供应链安全的需求。信息技术的飞速发展,数据库管理工具的需求也越来越迫切。然而,在众多软件中,要找到一款得心应手的数据库管理工具并不容易。今天,我向大家推荐一款功能...

Mac密码安全管理工具----Enpass(mac密码管理在哪里)

Enpassmac版是一款适用于macOS用户的密码安全管理工具,使用Enpass,你无需再为记住太多的密码和其他重要凭据而头疼了。Enpass把你的密码存放在一个安全的地方,然后通过一个主密码随时...

超实用的14款MySQL数据库管理工具

MySQL是当前流行的数据库引擎之一,具有成本低、速度快、体积小且开放源代码的优点。今天就给大家分享14款MySQL数据库管理工具。1.MySQLDumper这款软件的应用,有效解决使用PHP进行大数...

神器收藏:macOS最强工具清单,16.6k+星 awesome-macOS

神器收藏:macOS最强工具清单,16.6k+星标必看引言在macOS生态中,有一个备受瞩目的神仓库,汇集了最全面、最实用的macOS应用和工具清单。这个项目在GitHub上已获得超过16.6k的...

JetBrains DataGrip Mac中文破解版V2025.1下载安装教程

DataGripforMac是由JetBrains开发的数据库集成开发环境(IDE),专为数据库管理员和开发人员设计。它支持多种数据库(如MySQL、PostgreSQL、Oracle、SQ...

GIS坐标参考系统:EPSG、WKT和PROJ

在之前的教程中,我们介绍了什么是坐标参考系统(CRS)、坐标参考系统的组成部分以及投影坐标参考系统和地理坐标参考系统之间的一般差异。在这个教程中,我们将介绍CRS信息的不同存储方式。推荐:用...

【地理信息可视化】basemap(cartopy)+geopandas显示地图-03

importwarningswarnings.filterwarnings('ignore')importosimportnumpyasnpfromscipy....

字符识别之PaddleOcr介绍、安装与应用

paddleocr介绍paddleocr是一款轻量型字符识别工具库,支持多语言识别,支持pip安装与自定义训练。详细信息如下表所示。名称许可证当前版本下载地址(github地址)支持语言运行方式pi...

111.Python——基于pipenv打包PaddlePaddle的GUI项目

飞桨PaddlePaddle是百度的深度学习框架,用来做一些项目还是非常不错。但是打包就是一件非常麻烦的过程。在文中有讲过打包问题。29.Python程序打包成可执行文件——常见疑难问题解决办法。本文...

Shamos算法:一种在平面上找到最远点的方法

旋转卡尺算法简介Shamos算法,也叫旋转卡尺(Rotatingcalipers)算法,是一种用于解决计算几何问题的优化算法。它可以用来解决许多几何问题,包括计算点集的宽度或直径。算法的名称来源于其...