python将pdf文件中的表格按照原格式提取到excel中
作者:野牛程序员:2024-09-24 08:24:21python阅读 2676
python将pdf文件中的表格按照原格式提取到excel中
要从 PDF 中提取所有页面的表格,使用 pdfplumber 时可以遍历所有页面,并将每个页面的表格逐个提取出来。
pip install pdfplumber pandas openpyxl
以下是处理全部页面的示例代码:
代码示例:
import pdfplumber
import pandas as pd
# 打开 PDF 文件
pdf_path = "path_to_pdf_file.pdf"
with pdfplumber.open(pdf_path) as pdf:
# 获取第一页的表格作为示例
first_page = pdf.pages[0]
table = first_page.extract_table()
# 将表格转换为 DataFrame
df = pd.DataFrame(table)
# 将表格保存为 Excel
df.to_excel("output.xlsx", index=False)代码说明:
使用
pdfplumber.open()打开 PDF 文件。通过
pdf.pages获取 PDF 中的所有页面,并遍历每一页。对每一页调用
page.extract_table()提取表格,结果存入DataFrame。将所有页面的表格合并成一个大的
DataFrame,并添加一列来标注该表格属于哪个页面。最终保存为 Excel 文件。
此代码可以提取 PDF 中所有页面的表格,并保存在一个 Excel 文件中,每个页面的表格按顺序合并。如果 PDF 文件中的表格布局较复杂,可以调整表格处理逻辑。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

