컴퓨터/Python

국민연금 월불입액 파일 손상된 파일 xlsx로 정상적으로 저장하는 코드

풍경소리^^ 2025. 3. 25. 12:08
import os
import glob
import xlwings as xw

# 변환할 파일이 있는 디렉터리 경로
directory = r"C:\Users\newstep\Downloads"

# 최종 출력 파일명 설정 (xlsx로 바로 지정)
output_file = os.path.join(directory, "국민연금.xlsx")

# 파일 찾기
files = glob.glob(os.path.join(directory, "noticePaper*.xls"))

if files:
    input_file = files[0]  # 첫 번째 발견된 파일
    
    try:
        # 엑셀 열기 (Excel 애플리케이션 실행)
        app = xw.App(visible=False)  # 백그라운드에서 실행
        wb = app.books.open(input_file)  # 원본 파일 열기

        # 바로 xlsx 형식으로 저장
        wb.save(output_file)
        wb.close()
        app.quit()  # Excel 종료

        print(f"변환 완료: {output_file}")

        # 원본 xls 파일 삭제 (필요한 경우)
        os.remove(input_file)
        print(f"원본 파일 삭제: {input_file}")

    except Exception as e:
        print(f"변환 실패: {e}")

else:
    print("noticePaper*.xls 파일이 없습니다.")