컴퓨터/Python

python win32com.client xlsx 확장자 파일을 xls,xlsm 확장자 파일로 바꾸기

풍경소리^^ 2024. 10. 30. 16:15

 

import win32com.client as win32
import win32api
import os


def main():
    file_ext = os.path.splitext(FILE_AFTER)[1][1:]
    
    # Excel 객체 생성
    excel_app = win32.gencache.EnsureDispatch('Excel.Application')

    # 현재 작업 디렉토리
    current_path = os.getcwd()

    # 파일 경로 생성
    file_path1 = os.path.join(current_path, FILE_BEFORE)
    file_path2 = os.path.join(current_path, FILE_AFTER)

    # 기존 .xlsx 파일이 존재하는 경우 삭제
    if os.path.exists(file_path2):
        os.remove(file_path2)

    # .xls 파일 열기
    # wb = excel_app.Workbooks.Open("B:\python\jupyternotebook\pandas_엑셀투파이썬\mergecell1.xls")
    wb = excel_app.Workbooks.Open(file_path1)

    # .xlsx 파일로 저장하기
    if file_ext == "xls":
        # wb.SaveAs(file_path2, FileFormat=51) # xls 확장자를 xlsx 확장자로 바꾸기
        wb.SaveAs(file_path2, FileFormat=56) # xlsx 확장자를 xls 확장자로 바꾸기
    elif file_ext == "xlsm":
        wb.SaveAs(file_path2, FileFormat=52) # xlsx 확장자를 xlsm 확장자로 바꾸기
    # 파일 닫기
    wb.Close()

    # Excel 종료
    excel_app.Application.Quit()
    # 완료 메시지
    win32api.MessageBox(0, "작업을 완료했습니다.", "작업 완료", 0)

if __name__ == "__main__":
    FILE_BEFORE = "04missing.xlsx"  # .xlsx 파일 경로
    FILE_AFTER = "04missing.xls"  # .xlsm 파일 경로
    main()

 

xlsxtoanother.py
0.00MB