PDFのデータを

Python

pdfから表データの抽出

Javaのインストール

https://www.java.com/ja/download/help/download_options_ja.html

(宛先フォルダの変更は必要なし)

pip install tabula-py

pip install pandas

import tabula

import pandas

pdf_file = ‘C:/Users/wiki1/Desktop/xxx.pdf’

df = tabula.read_pdf(

pdf_file,

pages=’all’, #抽出ページ

password=None, #パスワード

lattice=True, #格子区切りがPDF内にある場合はTrue

)

df = df[0].rename(columns={‘元の列名’:’変更後の列名’})

df = df.to_excel(‘C:/Users/wiki1/Desktop/ooo.xlsx’, index=None)

※pages=’all’

40ページだけ取得したいときはpages=’40’とし、

40~45ページを取得したいときはpages=’40-45’とすること

※lattice=True

PDFの表には枠線がかけている箇所がいくつかある為、

lattice=Trueにすると一部のデータが抽出できなくなる

※PDFのセルが結合されている場合、正確に抽出できない

空の列「Unnamed:」が生まれる

※PDF内に表が2つ以上ある場合は、_のdfをdfsにすること

#PDF内に表が2つ以上ある場合

import tabula

import pandas

pdf_file = ‘C:/Users/wiki1/Desktop/xxx.pdf’

dfs = tabula.read_pdf(

pdf_file,

pages=’all’, #抽出ページ

password=None, #パスワード

lattice=True, #格子区切りがPDF内にある場合はTrue

)

for df in dfs:

display(df)

df = dfs[0].rename(columns={‘元の列名1’:’変更後の列名1’,’元の列名2’:’変更後の列名2’})

df = df.to_excel(‘C:/Users/wiki1/Desktop/ooo.xlsx’, index=None)

BACK