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

请求修正PDF转XLSX Python代码,保留原表格格式

修正PDF转XLSX并保留格式的Python代码

针对PDF表格转XLSX时格式丢失的问题,以下是优化后的代码,通过调整表格识别参数和添加格式保留逻辑来解决问题:

from path_name_mappings import destination_filed_xlsx, destination_path_pdf
import tabula
import pandas as pd
import os

def pdf_to_excel(pdf_file_path, excel_file_path):
    # 优化Tabula识别参数:针对带边框表格启用lattice模式,提升识别精度
    tables = tabula.read_pdf(
        pdf_file_path,
        pages='all',
        multiple_tables=True,
        lattice=True,  # 若为无框表格,替换为stream=True
        silent=True,
        pandas_options={'header': 0}  # 直接用PDF表格首行作为表头
    )

    with pd.ExcelWriter(excel_file_path, engine='xlsxwriter') as writer:
        workbook = writer.book
        # 定义匹配原表格的单元格格式:居中对齐、带边框
        cell_format = workbook.add_format({
            'align': 'center',
            'valign': 'vcenter',
            'border': 1
        })

        for i, table in enumerate(tables):
            # 填充合并单元格产生的空值,还原原表格结构
            table = table.ffill(axis=0).bfill(axis=0)
            # 重命名未识别的表头(适配你的PDF表格结构)
            table = table.rename(columns=lambda x: 'Godzina' if 'Unnamed' in str(x) else x)
            
            sheet_name = f'Sheet{i+1}'
            table.to_excel(writer, sheet_name=sheet_name, index=False)
            
            # 调整列宽并应用格式
            worksheet = writer.sheets[sheet_name]
            # 自动计算列宽
            for idx, col in enumerate(table.columns):
                max_len = max(table[col].astype(str).map(len).max(), len(col))
                worksheet.set_column(idx, idx, max_len + 2)
            # 给所有数据单元格应用格式
            for row_num in range(len(table)):
                for col_num in range(len(table.columns)):
                    worksheet.write(row_num + 1, col_num, table.iloc[row_num, col_num], cell_format)

def process_all_pdfs(pdf_folder, excel_folder):
    # 确保输出目录存在
    os.makedirs(excel_folder, exist_ok=True)
    for pdf_file in os.listdir(pdf_folder):
        if pdf_file.lower().endswith(".pdf"):
            pdf_file_path = os.path.join(pdf_folder, pdf_file)
            pdf_base_name = os.path.splitext(pdf_file)[0]
            excel_file_path = os.path.join(excel_folder, pdf_base_name + ".xlsx")
            pdf_to_excel(pdf_file_path, excel_file_path)

# 执行批量转换
process_all_pdfs(destination_path_pdf, destination_filed_xlsx)

核心优化说明:

  • 精准表格识别:用lattice=True适配带边框的PDF表格,避免列错位和内容提取错误;若你的表格无框线,切换为stream=True即可。
  • 空值修复:通过ffill和bfill填充合并单元格产生的空值,还原原表格的合并逻辑。
  • 格式还原:借助XLSXWriter设置单元格边框、居中对齐,并自动调整列宽,让导出的Excel和原PDF表格样式一致。
  • 鲁棒性提升:添加目录自动创建、大小写兼容的PDF后缀判断,避免运行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:06:21