콘솔워크

파이썬 엑셀 파일 합치는 프로그램 본문

프로그래밍/python

파이썬 엑셀 파일 합치는 프로그램

콘솔워크 2023. 6. 2. 20:52
반응형

패키지 설치합니다.

pip install pandas

 

 

 

한 폴더 내의 엑셀들을 하나로 합치는 기능을 담은 class 입니다.

import os
import pandas as pd
from datetime import datetime

class ExcelWorkFeature:
    def __init__(self) -> None:
        pass

    # 폴더 내의 엑셀을 합치기
    def combine_excel(self, folder_path: str) -> None:
        # folder_path : 엑셀 파일 경로
        print(folder_path)

        # 폴더 내 모든 엑셀 파일 경로 가져오기
        excel_files = [f for f in os.listdir(folder_path) if f.endswith(".xlsx")]
        excel_files += [f for f in os.listdir(folder_path) if f.endswith(".xls")]

        # 모든 엑셀 파일을 데이터프레임으로 읽어들이기
        dfs = []
        for file in excel_files:
            file_path = os.path.join(folder_path, file)
            df = pd.read_excel(file_path)
            dfs.append(df)

        # 데이터프레임들을 하나로 합치기
        combined_df = pd.concat(dfs)

        now = datetime.now().strftime("%Y%m%d%H%M%S")
        output_file_path = "엑셀합치기결과_{now}.xlsx"

        # 새로운 엑셀 파일로 저장
        combined_df.to_excel(output_file_path, index=False, engine="xlsxwriter")

        return output_file_path


ExcelWorkFeature().combine_excel(r"C:\Users\consolework\Documents\폴더")

파라미터로 합치기 원하는 엑셀이 들어있는 폴더를 입력하고, combine 엑셀 함수를 실행하면 폴더내의 엑셀들이 하나로 합쳐집니다.

 

 

주의할점은 폴더내에 있는 엑셀들이 모두 같은 양식(열)이어야 합니다.

 

반응형