星云点击:星空遥控器
120.47M · 2026-02-04
在日常办公、数据分析或信息归档过程中,我们经常会遇到包含表格数据的 PDF 文件。然而,PDF 本质上是一种用于展示和打印的格式,并非为数据处理而设计,因此直接从中提取结构化数据颇具挑战。幸运的是,借助 Python 强大的生态工具,我们可以自动化地从 PDF 中识别并提取表格内容,并将其保存为便于后续处理的 TXT 或 Excel(.xlsx)格式。
本文将介绍两种主流且高效的开源库——Tabula-py 和 Camelot-py,并通过完整示例演示如何将 PDF 表格数据导出为 TXT 和 Excel 文件。
首先,确保你的系统已安装 Java(Tabula 依赖 Java 运行),然后通过 pip 安装所需库:
# 安装 Tabula-py(基于 Java 的 Tabula 工具)
pip install tabula-py pandas openpyxl
# 或安装 Camelot-py(基于 Ghostscript 和 OpenCV,更强大但配置稍复杂)
pip install camelot-py[cv] pandas openpyxl
Tabula-py 是对 Java 工具 Tabula 的 Python 封装,适合处理结构清晰、边界线完整的表格。
import tabula
import pandas as pd
# 指定 PDF 文件路径
pdf_path = "example_table.pdf"
# 提取所有页面的表格(返回 DataFrame 列表)
tables = tabula.read_pdf(pdf_path, pages="all", multiple_tables=True)
# 合并所有表格(或按需处理单个)
combined_df = pd.concat(tables, ignore_index=True)
# 导出为 Excel
combined_df.to_excel("output.xlsx", index=False)
# 导出为 TXT(以制表符分隔)
combined_df.to_csv("output.txt", sep="t", index=False, na_rep="")
print("表格已成功导出为 Excel 和 TXT 文件!")
Camelot 提供了两种解析模式:lattice(适用于有边框的表格)和 stream(适用于无边框但对齐良好的表格),灵活性更高。
import camelot
import pandas as pd
pdf_path = "example_table.pdf"
# 使用 'lattice' 模式(有边框表格)
tables = camelot.read_pdf(pdf_path, pages="all", flavor="lattice")
# 若表格无边框,可尝试:
# tables = camelot.read_pdf(pdf_path, pages="all", flavor="stream")
if tables:
# 合并所有表格
dfs = [table.df for table in tables]
combined_df = pd.concat(dfs, ignore_index=True)
# 清理列名(Camelot 默认无列名,第一行为数据)
# 如需将第一行设为列名:
# combined_df.columns = combined_df.iloc[0]
# combined_df = combined_df[1:].reset_index(drop=True)
# 导出
combined_df.to_excel("camelot_output.xlsx", index=False)
combined_df.to_csv("camelot_output.txt", sep="t", index=False, header=False)
print(f"成功提取 {len(tables)} 个表格,已保存为 Excel 和 TXT。")
else:
print("未检测到任何表格。")
tables[0].plot())。pandas.DataFrame.to_excel)。t)或逗号分隔,轻量且兼容性强(使用 to_csv 并指定 sep)。表格识别不全?
pages="1,3,5"。table_areas 参数手动划定区域。中文乱码?
encoding='utf-8-sig'。性能优化
Python 为 PDF 表格数据提取提供了强大而灵活的解决方案。Tabula-py 适合快速上手的标准表格,而 Camelot-py 则在复杂场景下表现更优。结合 pandas 的数据处理能力,我们可以轻松将“不可编辑”的 PDF 表格转化为结构化的 TXT 或 Excel 文件,大幅提升数据再利用效率。
无论你是财务人员、数据分析师还是自动化开发者,掌握这些工具都将显著简化你的工作流程。快试试吧!