728x90

파이썬에서 PDF 파일을 읽어와서 엑셀 파일로 변환하기 위해서는 몇 가지 라이브러리를 사용해야 합니다.
주로 PyPDF2 또는 pdfplumber를 사용하여 PDF 파일을 읽고, pandas를 사용하여 데이터를 가공하여 엑셀 파일로 저장할 수 있습니다.

pdfplumber 는 PDF 파일의 각 문자, 사각형, 선에 대한 상세한 정보를 제공하고 텍스트와 표를 쉽게 추출할 수 있는 라이브러리로, 데이터 분석 및 자동화 작업에 유용한 도구입니다.

https://github.com/jsvine/pdfplumber

1. 라이브러리 설치

먼저 pdfplumber 라이브러리를 설치합니다.(pip, anaconda, pipenv 환경 구성에 따라 설치 합니다.)

1. pip
pip install pdfplumber

2. anaconda
conda install -c conda-forge pdfplumber

3. pipenv
pipenv install pdfplumber

2. 테이블 추출하기

pdf 를 추출하기 위해 pdfplumber.open(file) 함수를 이용하여 pdf를 추출합니다.

import os  
import pdfplumber  
import pandas as pd  


file_path = os.getcwd()+"/contents/"  
pdf_name = "file.pdf"  
pdf_file_path = file_path + pdf_name  

# PDF 파일 열기  
pdf = pdfplumber.open(pdf_file_path)  

pages = pdf.pages  
print("총 페이지 수 : ", len(pages))  

tables = []  

# 1. 페이지에서 표 데이터 추출하기  
for each in pages:  
    table = each.extract_tables()  
    tables.extend(table)

3. 데이터 프레임으로 변환

# 2. 데이터 프레임으로 변환  
df = pd.DataFrame(tables[1:], columns=[tables[0]])  

# 3. 데이터프레임을 엑셀 파일로 저장  
excel_file_path = file_path + "file.xlsx"  
df.to_excel(excel_file_path, index=False, engine='openpyxl')

print(f'DataFrame이 {excel_file_path}에 저장 되었습니다.')

openpyxl 라이브러리가 설치되어 있지 않은 경우, 설치 하여 주세요.

728x90
반응형

+ Recent posts