콘솔워크

xlsx, xls 변환 함수 본문

프로그래밍/python

xlsx, xls 변환 함수

이휘재123 2023. 5. 8. 17:29
반응형
import win32com.client as win32


def xls_to_xlsx(source):
    if not str(source).find("xls") > -1:
        return
    excel = win32.Dispatch("Excel.Application")
    # excel = win32.gencache.EnsureDispatch("Excel.Application")
    wb = excel.Workbooks.Open(source)

    xlsx_file = source + "x"
    if os.path.isfile(xlsx_file):
        os.remove(xlsx_file)
    wb.SaveAs(xlsx_file, FileFormat=51)  # FileFormat = 51 is for .xlsx extension
    wb.Close()  # FileFormat = 56 is for .xls extension
    excel.Application.Quit()


def xlsx_to_xls(source):
    if not str(source).find("xlsx") > -1:
        return

    if not os.path.isfile(source):
        return

    # excel = win32.gencache.EnsureDispatch("Excel.Application")
    excel = win32.Dispatch("Excel.Application")

    wb = excel.Workbooks.Open(source)

    print("xlsx_to_xls")

    xls_file = source[:-1]
    if os.path.isfile(xls_file):
        os.remove(xls_file)
    wb.SaveAs(xls_file, FileFormat=56)  # FileFormat = 51 is for .xlsx extension
    wb.Close()  # FileFormat = 56 is for .xls extension
    excel.Application.Quit()

    os.remove(source)

    return xls_file
반응형