Search code examples
pythonexcelpywin32sap-gui

How to close an Excel file opened by another application? Using python with win32com.client


I am using Python to automate a process in SAP GUI, with the library win32com.client.

Everything was going right, until the SAP open an Excel file on the final of the process.

I need to close this file (and only this file).

The original script came from a .bas file, and I rewrote the necessary to Python. In the .bas file the Excel file was closed with Workbooks("YVA05_********").Close

Please help me with a simple line to close only this Excel file (like the old code, but for my Python application) and I will be eternally grateful.

Cheers

from datetime import datetime
from win32com.client import Dispatch
import win32com.client
import time
import subprocess


excel = Dispatch("Excel.Application")

today = datetime.today()
today_modified = "{:02}.{:02}.{}".format(today.month, today.day, today.year)
month_init = "{:02}.01.{}".format(today.month, today.year)
file_name = f"{today.year}-{today.month:02}"

def extract_data_process(month_init,today_modified,file_name,session):
    session.findById("wnd[0]/usr/ctxtS_SAUDAT-LOW").text = f"{month_init}"
    session.findById("wnd[0]/usr/ctxtS_SAUDAT-HIGH").text = f"{today_modified}"
    session.findById("wnd[0]/tbar[1]/btn[8]").press()
    time.sleep(6)
    session.findById("wnd[0]/usr/cntlCONTAINER/shellcont/shell").pressToolbarContextButton("&MB_EXPORT")
    session.findById("wnd[0]/usr/cntlCONTAINER/shellcont/shell").selectContextMenuItem("&XXL")
    session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\\Users\\*****************"
    session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = f"YVA05_{file_name}.XLSX"
    session.findById("wnd[1]/tbar[0]/btn[11]").press()

    # Here the excel is opened

    session.findById("wnd[0]/tbar[0]/btn[3]").press



pathname = r"C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe"

subprocess.Popen(pathname)
time.sleep(8)


SapGuiAuto = win32com.client.GetObject('SAPGUI')
if not type(SapGuiAuto) == win32com.client.CDispatch:
    exit()

application = SapGuiAuto.GetScriptingEngine
if not type(application) == win32com.client.CDispatch:
    SapGuiAuto = None
    exit()
    
connection = application.OpenConnection("*****************", True)
if not type(connection) == win32com.client.CDispatch:
    application = None
    SapGuiAuto = None
    exit()

session = connection.Children(0)
if not type(session) == win32com.client.CDispatch:
    connection = None
    application = None
    SapGuiAuto = None
    exit()


session.findById("wnd[0]/usr/txtRSYST-MANDT").text = "***"
session.findById("wnd[0]/usr/txtRSYST-BNAME").text = "***********"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").text = "**************"
session.findById("wnd[0]/usr/txtRSYST-LANGU").text = "EN"
session.findById("wnd[0]").sendVKey(0)

# time.sleep(2)
# session.findById("wnd[1]").sendVKey(0)
# time.sleep(2)

session.findById("wnd[0]/tbar[0]/okcd").text = "****"
session.findById("wnd[0]/tbar[0]/btn[0]").press()
session.findById("wnd[0]/tbar[1]/btn[17]").press()
session.findById("wnd[1]/usr/txtV-LOW").text = "*********"
session.findById("wnd[1]/usr/txtENAME-LOW").text = ""
session.findById("wnd[1]/tbar[0]/btn[8]").press()

extract_data_process(month_init,today_modified,file_name,session)

Solution

  • Hopefully, this function will solve your problem

    import os
    
    def close():
    
        try:
            os.system('TASKKILL /F /IM excel.exe')
    
        except Exception:
            print("KU")
    
    close()