DEV Community

h451ke
h451ke

Posted on

Extracting Multi-Page PDF Tables into Real Excel Formulas (Not Text Strings) with Python & pdfplumber

Anyone who has tried converting a 15-page bank statement or supplier price list from PDF to Excel knows the three classic bugs that ruin naive scripts:

  1. Every page turns into a separate table — with the header row duplicated 15 times inside the sheet.
  2. Numbers export as text strings ("$2,450.00" or "(148.20)") — so Excel =SUM() silently returns 0 and Pivot Tables break.
  3. Borderless tables collapse into one column when a PDF uses whitespace alignment instead of vector grid lines.

Here is the exact Python pattern (pdfplumber + openpyxl) we use in production to stitch multi-page PDF tables into clean, formula-ready .xlsx files — plus a quick pattern for diffing two exported spreadsheets by key column instead of broken line numbers.


1. Stitching Multi-Page Tables Without Duplicate Headers

When a ledger spans consecutive pages, pdfplumber returns one table array per page. Before appending rows, normalize the header signature (lowercase + collapse whitespace) and compare column counts:

import re, pdfplumber

def norm_header(row):
    return [re.sub(r"\s+", " ", (c or "").strip().lower()) for c in row]

def extract_stitched_tables(pdf_bytes: bytes, borderless: bool = False):
    settings = (
        {"vertical_strategy": "text", "horizontal_strategy": "text"}
        if borderless
        else {"vertical_strategy": "lines", "horizontal_strategy": "lines"}
    )
    merged = []
    with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
        for page in pdf.pages:
            for tbl in page.extract_tables(settings) or []:
                rows = [[(c or "").strip() for c in r] for r in tbl if any(r)]
                if len(rows) < 2:
                    continue
                if (
                    merged
                    and len(rows[0]) == len(merged[-1]["headers"])
                    and norm_header(rows[0]) == norm_header(merged[-1]["headers"])
                ):
                    merged[-1]["rows"].extend(rows[1:])
                else:
                    merged.append({"headers": rows[0], "rows": rows[1:]})
    return merged
Enter fullscreen mode Exit fullscreen mode

This single check turns a 12-page bank statement with repeated headers into one continuous table.


2. Casting Currency & Accounting Parentheses to Real Excel Floats

In accounting PDFs, negative amounts often appear as (148.20) or -$148.20. If you write them raw to openpyxl, Excel treats them as strings. Parse them into native Python floats before writing:

import re

NUM_RE = re.compile(r"^\s*(\(?)\s*([+-]?)\s*[$€£¥]?\s*(\d{1,3}(?:,\d{3})*|\d+)(?:\.(\d+))?\s*(\)?)\s*$")

def parse_cell(value: str):
    m = NUM_RE.match(value)
    if not m:
        return value
    lpar, sign, whole, frac, rpar = m.groups()
    if bool(lpar) != bool(rpar):
        return value
    num = float(f"{whole.replace(',', '')}.{frac or '0'}")
    if sign == "-" or lpar:
        num = -num
    return int(num) if frac is None else num
Enter fullscreen mode Exit fullscreen mode

Once written as numeric values with frozen top headers (ws.freeze_panes = "A2") and UTF-8 BOM for CSV (utf-8-sig), finance teams can immediately run =SUM() and Pivot Tables with zero cleanup.


3. Comparing Two Updated Spreadsheets by Key Column (Not Row Index)

Once you extract this month's supplier catalog or bank statement, the very next task is usually: "What changed since last month?"

Standard text diff tools explode when someone inserts 3 new SKUs at row 4 — shifting every row below it. Keying rows by an ID/SKU column (dict[key_val, row]) surfaces only true ADDED, REMOVED, and old → new cell edits cleanly.


Try It Live Without Installing Anything

If you want to test these workflows directly in the browser (no signup, zero server-side file retention — everything runs in RAM and streams back):

What's the nastiest PDF table format you've had to parse in Python? Multi-line wrapped descriptions or rotated landscape tables usually give me the most grief!

Top comments (0)