作为财务、审计、数据分析的打工人,你是否经常遇到这样的场景:收到几十页的PDF报告,需要手动复制其中的表格到Excel,稍有不慎就错位乱码,加班到深夜……
本文用 5个真实案例 + 10段即用代码,教你用Python实现PDF表格全自动提取→清洗→导出Excel,从此告别复制粘贴!文末附完整工具包。
一、PDF表格提取的三大痛点
- 格式混乱
- 中文乱码
- 扫描件难题:图片型PDF无法直接读取(需OCR,文末附方案)
二、工具链:pdfplumber + pandas
2.1 环境准备
pip install pdfplumber pandas openpyxl
2.2 核心工具说明
三、基础案例:提取简单表格
案例1:单页PDF → 单Sheet Excel
目标:将如下结构的销售数据表提取到Excel(无需图片,直接模拟数据):
PDF表格示例
产品 销量 单价 销售额
手机 100 2000 200000
笔记本 50 5000 250000
import pdfplumber import pandas as pd
def pdf_to_excel(pdf_path, excel_path): with pdfplumber.open(pdf_path) as pdf: first_page = pdf.pages[0] table = first_page.extract_table() df = pd.DataFrame(table[1:], columns=table[0]) df.to_excel(excel_path, index=False)
from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt="产品 销量 单价 销售额", ln=True) pdf.cell(200, 10, txt="手机 100 2000 200000", ln=True) pdf.cell(200, 10, txt="笔记本 50 5000 250000", ln=True) pdf.output("sales.pdf")
pdf_to_excel("sales.pdf", "sales.xlsx")
输出Excel效果
四、进阶案例:处理复杂表格
案例2:多页PDF → 多Sheet Excel
目标:将年报中的多页表格合并到一个Excel的不同Sheet
def multi_page_to_excel(pdf_path, excel_path): with pdfplumber.open(pdf_path) as pdf: with pd.ExcelWriter(excel_path, engine='openpyxl') as writer: for i, page in enumerate(pdf.pages): table = page.extract_table() if table: df = pd.DataFrame(table[1:], columns=table[0]) df.to_excel(writer, sheet_name=f"Sheet_{i+1}", index=False)
pdf = FPDF() for _ in range(2): pdf.add_page() pdf.cell(200, 10, txt="产品 销量 单价 销售额", ln=True) pdf.cell(200, 10, txt="手机 100 2000 200000", ln=True) pdf.output("multi_page.pdf")
multi_page_to_excel("multi_page.pdf", "multi_page.xlsx")
案例3:处理合并单元格
目标:提取如下结构的合并单元格表格:
PDF表格示例
地区 城市 销售额
华东 上海 500
杭州 300
def handle_merged_cells(pdf_path): with pdfplumber.open(pdf_path) as pdf: page = pdf.pages[0] table = page.extract_table({ "vertical_strategy": "lines", "horizontal_strategy": "lines" }) df = pd.DataFrame(table) df.iloc[1:3, 0] = df.iloc[0, 0] return df
pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt="地区 城市 销售额", ln=True) pdf.cell(200, 10, txt="华东 上海 500", ln=True) pdf.cell(200, 10, txt=" 杭州 300", ln=True) pdf.output("merged.pdf")
df = handle_merged_cells("merged.pdf") df.to_excel("merged.xlsx")
输出Excel效果
案例4:处理扫描件PDF(OCR方案)
目标:图片型PDF的文字识别
from pdf2image import convert_from_path import pytesseract import cv2 import numpy as np
def ocr_pdf_table(pdf_path): images = convert_from_path(pdf_path, 500) all_dfs = [] for img in images: img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY) text = pytesseract.image_to_string(thresh) # 解析文本为表格 rows = [line.split() for line in text.split('\n') if line.strip()] df = pd.DataFrame(rows[1:], columns=rows[0]) all_dfs.append(df) return pd.concat(all_dfs)
# 生成测试图片型PDF(需提前截图为PDF) # 假设扫描件内容与案例1相同 final_df = ocr_pdf_table("scanned.pdf") final_df.to_excel("scanned_output.xlsx")
五、避坑指南:常见问题解决
5.1 中文乱码问题
with pdfplumber.open(pdf_path, encoding="UTF-8") as pdf: ... df.to_excel("output.xlsx", encoding="utf-8-sig")
5.2 表格错位校正
table = page.extract_table({ "vertical_strategy": "text", "horizontal_strategy": "text", "snap_tolerance": 4 })
5.3 处理空白单元格
df.fillna("N/A", inplace=True) df.dropna(how="all", inplace=True)
阅读原文:原文链接
该文章在 2025/8/28 15:41:56 编辑过