컴퓨터/Python

python xlsx→xls xlsx→xlsm 파일 변환

풍경소리^^ 2024. 11. 5. 15:15

xlsxtoanother.py
0.00MB

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()

 

chatgpt

main함수에서 target 파일형식 지정

import win32com.client as win32
import win32api
import os

def convert_excel(file_path1, file_path2, target_format):
    """
    Converts an Excel file to the desired format.
    :param file_path1: Input file path
    :param file_path2: Output file path
    :param target_format: Target format for the output file (51 for .xlsx, 56 for .xls, 52 for .xlsm)
    """
    try:
        # Create Excel Application Object
        excel_app = win32.gencache.EnsureDispatch('Excel.Application')

        # Delete existing target file if it exists
        if os.path.exists(file_path2):
            os.remove(file_path2)

        # Open the source Excel file
        if not os.path.exists(file_path1):
            print(f"File not found: {file_path1}")
            return

        wb = excel_app.Workbooks.Open(file_path1)

        # Save the file in the target format
        wb.SaveAs(file_path2, FileFormat=target_format)
        # print(f"Successfully converted: {file_path1} to {file_path2}")

        # Close the workbook
        wb.Close()

        # Delete the original file after successful conversion
        os.remove(file_path1)
        # print(f"Deleted original file: {file_path1}")

    except Exception as e:
        print(f"Error processing {file_path1}: {e}")
    finally:
        # Quit the Excel application
        excel_app.Application.Quit()


if __name__ == "__main__":
    # Define the source and target formats
    SOURCE_EXTENSION = "xlsx"  # Source file extension: "xls", "xlsx", or "xlsm"
    TARGET_EXTENSION = "xls"  # Target file extension: "xls", "xlsx", or "xlsm"
    TARGET_FORMAT_MAP = {"xlsx": 51, "xls": 56, "xlsm": 52}

    if TARGET_EXTENSION not in TARGET_FORMAT_MAP:
        print(f"Unsupported target extension: {TARGET_EXTENSION}")
        exit()

    target_format = TARGET_FORMAT_MAP[TARGET_EXTENSION]

    # Absolute path for the input folder
    current_path = os.path.abspath(r".\다운로드")  # Use absolute path
    file_list = os.listdir(current_path)  # List files in the directory

    for i in file_list:
        FILE_BEFORE = os.path.join(current_path, i)
        file_ext = os.path.splitext(FILE_BEFORE)[1][1:]  # Get the file extension without the dot

        if file_ext != SOURCE_EXTENSION:
            print(f"Skipping unsupported source file: {FILE_BEFORE}")
            continue

        FILE_AFTER = os.path.splitext(FILE_BEFORE)[0] + f".{TARGET_EXTENSION}"

        # print(f"Processing: {FILE_BEFORE}")
        # print(f"Target: {FILE_AFTER}")

        # Perform the conversion
        convert_excel(FILE_BEFORE, FILE_AFTER, target_format)

    # Completion message
    win32api.MessageBox(0, "작업을 완료했습니다.", "작업 완료", 0)