콘솔워크

win32com.client.Dispatch("Excel.Application") Copy Sheet 본문

프로그래밍/python

win32com.client.Dispatch("Excel.Application") Copy Sheet

콘솔워크 2022. 9. 7. 15:00
반응형

target파일에 source에 있는 시트를 붙여넣는 코드이다.

import win32com.client

def copy_sheet(source, target):

    try:
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible = False
        excel.DisplayAlerts = False
        wb1 = excel.Workbooks.Open(source)
        wb2 = excel.Workbooks.Open(target)
        source_ws = wb1.Worksheets("SourceSheet")
        target_ws = wb2.Worksheets("TargetSheet")
        source_ws.Range("A:Z").Copy(target_ws.Range("A:Z"))
        wb2.Save()

    except Exception as e:
        print(e)

    finally:
        try:
            wb1.Close()
            wb2.Close()
        except Exception as e:
            print(e)
        excel.Quit()

 

 

라이브러리설치

pip install pywin32
반응형