Python code to convert PDF file to Excel Spreadsheet

CK CK 3788 
Created at
Updated at  
700 0 0

The most popular Python library for reading PDF files is PyPDF2, offering functionalities for extracting text, metadata, and manipulating pages. Other libraries like PyMuPDF (fitz) provide similar capabilities with potentially better performance for complex PDFs, while libraries like Tika leverage Apache Tika server for broader document processing capabilities beyond just PDFs. The choice depends on the specific needs and complexity of the task.

To determine if a PDF file contains table cells with numbers, you would need to use a PDF processing library (like PyPDF2 in Python or similar libraries in other languages) to extract the text content, likely focusing on table structures if they're explicitly defined in the PDF. Then, you'd need to iterate through the extracted text, identifying table cell contents and using regular expressions or other string manipulation techniques to check if those cells contain numerical values. Simple text searches won't suffice for complex table structures or images of tables.

To convert a PDF file into an Excel spreadsheet, you can use the PyPDF2 library to extract text from the PDF and the pandas library to write the extracted data into an Excel file. For more structured PDFs, the pdfplumber library is more suitable as it can handle tables better.

 

Here’s a script to perform the conversion:

 

Step 1: Install Required Libraries

pip install pandas openpyxl pdfplumber

 

Step 2: Python Script

import pandas as pd
import pdfplumber

def pdf_to_excel(pdf_path, excel_path):
    """
    Convert a PDF file into an Excel spreadsheet.

    Args:
        pdf_path (str): Path to the input PDF file.
        excel_path (str): Path to the output Excel file.
    """
    # Open the PDF file
    with pdfplumber.open(pdf_path) as pdf:
        all_data = []
        for page_number, page in enumerate(pdf.pages, start=1):
            print(f"Processing page {page_number}...")
            # Extract tables from the page
            tables = page.extract_tables()
            for table in tables:
                # Convert table to a DataFrame
                df = pd.DataFrame(table)
                all_data.append(df)

        # Combine all extracted tables into a single Excel file
        with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:
            for i, df in enumerate(all_data):
                sheet_name = f"Page_{i+1}"
                df.to_excel(writer, sheet_name=sheet_name, index=False, header=False)
    print(f"PDF data has been saved to {excel_path}")

# Example usage
pdf_path = "example.pdf"  # Replace with your PDF file path
excel_path = "output.xlsx"  # Replace with desired Excel output path
pdf_to_excel(pdf_path, excel_path)

 

Explanation:

  1. PDF Reading:
    • The pdfplumber library extracts structured tables from the PDF.
  2. Excel Writing:
    • Each table extracted from the PDF is written to a separate sheet in the Excel file.
    • The openpyxl engine ensures compatibility with Excel.
  3. Customization:
    • You can adjust the script to process specific pages or handle text outside tables if needed.

 

Output:

  • The resulting Excel file will have one sheet per table extracted from the PDF. Each sheet is labeled with the page number.
Tags PDF PDF to Excel PyMuPDF PyPDF2 pandas pdfplumber Facebook X
Comments 0
Similar posts
  1. Python Quizs
    501
  2. Simple Example to get the total number of records in BigQuery with Python
    666
  3. Create PDF Files On the Fly in C#
    1,002
  1. Automated API Documentation with PyCharm
    891
  2. How to install python 3.9 alongside python 3.8 on CentOS 7?
    710
  3. How to run Python 3.9 on Mac?
    650
  4. Python Quizs
    501
  5. Automated OpenAPI documentation for a Python Flask API
    1,120
  6. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,029
  7. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  8. Garbage Collection when your system does not have enough memory in your Python App
    1,011
  9. Method to maximize full CPU performance with Python
    315
  10. How do I get the maximum available of thread in python?
    990
  11. Using Queue Algorithm with Redis - RPUSH and LPOP
    769
  12. Use cache concept with Redis : Let's do Redis programming with Python
    531
  13. Installing Python 3.8 in a venv environment on CentOS 7
    463
  14. CUDA versus OpenCL
    578
  15. Simple gRPC server based on Python
    394
  16. Python script to list files on your Google Drive and download one of them
    940
  17. Coinbase Python API - Basic Example
    461
  18. AWS Lambda Code Example based on Python
    333
  19. Python code using GPU on CentOS with AWS
    1,251
  20. Video Scence Detection with PySceneDetect
    2,320
  21. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,442
  22. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    908
  23. Deleting a specific user voice from the original audio track with Python
    548
  24. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    439
  25. Creating mp3 audio file based on the text input with Python
    465
  26. Implementing Text To Speech / Audio with Python3 and pyttsx3
    355
  27. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  28. Python Simplified Assignment Operators
    533
  29. Trackback module used for Python Threading debugging
    843
  30. Python Flask with simple HTML files to server web pages along with API
    927
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    39
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,611
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    243
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    582
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    216
  30. Understanding Data Lineage
    260