컴퓨터/Python

python pandas 폴더 내 엑셀파일 합치기

풍경소리^^ 2024. 12. 24. 16:53
# 단축형 코드
import pandas as pd
import os
import glob
import win32api

# 현재 위치에서 data 폴더 경로 설정
# base_location = os.getcwd()  # 현재 디렉토리
# data_location = os.path.join(base_location, 'data')  # data 폴더 경로
data_location = './data'
SKIP_ROWS = 5 # 제목 위 공란 줄 갯수

# data 폴더 존재 여부 확인
# if not os.path.exists(data_location):
#     print(f"'{data_location}' 폴더가 존재하지 않습니다.")
#     return

# data 폴더 내 .xls 파일 찾기
excels = glob.glob(os.path.join(data_location, '*.xls'))
print("대상 엑셀 파일:", excels)

# if len(excels) == 0:
#     print("합칠 파일이 없습니다.")

# 드롭할 컬럼 목록
dropcols = ['전자세금계산서분류', '전자세금계산서종류', '발급유형', '비고', '영수/청구 구분',
            '공급자 이메일', '공급받는자 이메일1', '공급받는자 이메일2', '품목일자', '품목명', '품목규격', '품목수량',
            '품목단가', '품목공급가액', '품목세액', '품목비고']

# 첫 번째 파일 읽기 및 초기화
df_total = pd.read_excel(excels[0], skiprows=SKIP_ROWS) # 제목 위 공란 줄 갯수
# print(f"{excels[0]} 파일 {df_total.shape[0]} 행")

# 나머지 파일 읽기 및 데이터프레임 병합
for item in excels[1:]:
# for item in excel_list[1:]:
    df = pd.read_excel(item, skiprows=SKIP_ROWS) # 제목 위 공란 줄 갯수
    # print(f"{item} 파일 {df.shape[0]} 행")
    df_total = pd.concat([df_total, df], axis=0)

# 드롭할 컬럼 제거
df_total = df_total.drop(columns=[col for col in dropcols if col in df_total.columns])

# 결과 파일 저장 경로
output_file = os.path.join(data_location, "hometax_pandas_xlsxWriter.xlsx")
df_total.to_excel(output_file, index=False, sheet_name="Sheet1")
print(f"{output_file} 파일 저장 완료!")

# 작업 완료 메시지 박스 표시
win32api.MessageBox(0, "작업을 완료했습니다.", "작업 완료", 0)