You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Camelot提取PDF多表后合并至Excel报错,类型不匹配问题求解

解决Camelot提取表格合并到Excel的报错问题

你遇到的错误核心原因是:camelot.read_pdf()返回的TableList集合里,每个元素是Camelot专属的Table对象,而pd.concat()只能处理Pandas的Series或DataFrame类型,直接传入Table对象自然会报错。

修正步骤

只需要先把每个Table对象转换成Pandas DataFrame,再进行合并即可:

  1. 遍历所有提取到的Table,通过每个Table的.df属性完成类型转换
  2. 将转换后的DataFrame存入列表
  3. 用pd.concat()合并列表中的DataFrame,最后保存到Excel

修正后的代码

import camelot
import pandas as pd

# 提取PDF中所有表格
tables = camelot.read_pdf('foo.pdf', pages="all")

# 把每个Table转为DataFrame并收集到列表
df_list = [table.df for table in tables]

# 合并并保存
if df_list:
    merged_df = pd.concat(df_list, ignore_index=True)
    # index=False 避免把行索引写入Excel
    merged_df.to_excel('foo.xlsx', index=False)
else:
    print("未从PDF中提取到任何表格")

额外优化:处理重复表头

如果PDF里的每个表格都带重复表头,合并后会出现多份表头行,可以加一步过滤处理:

import camelot
import pandas as pd

tables = camelot.read_pdf('foo.pdf', pages="all")
df_list = [table.df for table in tables]

if df_list:
    # 获取第一份表格的表头
    header = df_list[0].iloc[0]
    filtered_dfs = []
    
    for df in df_list:
        # 过滤掉和表头完全一致的行,再重新设置列名
        filtered_df = df[~df.apply(lambda row: row.equals(header), axis=1)]
        filtered_df.columns = header
        filtered_dfs.append(filtered_df)
    
    merged_df = pd.concat(filtered_dfs, ignore_index=True)
    merged_df.to_excel('foo.xlsx', index=False)
else:
    print("未从PDF中提取到任何表格")

内容的提问来源于stack exchange,提问作者Andreea Elena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:35:11