Ice Kame
Ice Kame

Reputation: 113

Exporting Excel file from SAP with Python Script

I have a adaptation of a SAP GUI script (original in VB) to Python:

#Connect with the SAP
SapGuiAuto = win32com.client.GetObject("SAPGUI")
application = SapGuiAuto.GetScriptingEngine
connection = application.Children(0)
session = connection.Children(0)

#Open the search window
session.findById("wnd[0]").maximize()
session.findById("wnd[0]/tbar[0]/okcd").text = information1
session.findById("wnd[0]").sendVKey(0)
session.findById("wnd[0]/usr/ctxtS_BUKRS-LOW").text = information2
session.findById("wnd[0]/usr/ctxtS_TPLST-LOW").text = informaton3
session.findById("wnd[0]/usr/ctxtS_TPLST-HIGH").text = information4
session.findById("wnd[0]/usr/ctxtS_ERDAT-LOW").text = information5
session.findById("wnd[0]/usr/ctxtS_ERDAT-HIGH").text = information6

#Charge to clipboard the list of ids
lista = open('list.txt')
df = ""
for lines in lista.readlines():
    df = df + " " + str(lines)
print(df)
pyperclip.copy(df)

#Open Window with mutiple select
session.findById("wnd[0]/usr/btn%_S_TKNUM_%_APP_%-VALU_PUSH").press()

#Paste ids list
session.findById("wnd[1]/tbar[0]/btn[24]").press()
session.findById("wnd[1]/tbar[0]/btn[8]").press()

#Search
session.findById("wnd[0]").sendVKey(8)

#Select to export Excel file
session.findById("wnd[0]/mbar/menu[0]/menu[3]/menu[1]").select()
session.findById("wnd[1]/tbar[0]/btn[0]").press()

And then I have no control of 'Save as' window, the SAP GUI script doesn't detect this and all my tests doesn't work too.

I found a similar problem of 2019 here, but no answers or solution ideas: Exporting with SAP using Python

Upvotes: 1

Views: 4929

Answers (1)

ScriptMan
ScriptMan

Reputation: 1625

Suppose the file type is xlsx. In this case I used the following workaround:

...
#Select to export Excel file
session.findById("wnd[0]/mbar/menu[0]/menu[3]/menu[1]").select()

myFileName = "c:\tmp\Test.xlsx"
Set Wshell = CreateObject("WScript.Shell")
Wshell.Run "c:\tmp\SaveFile.vbs" & " " & myFileName, 1, False

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

SaveFile.vbs:

if wscript.arguments.count > 0 then

 Set fso = CreateObject("Scripting.FileSystemObject")
 If fso.fileExists(wscript.arguments(0)) Then
  Set myfile = fso.GetFile(wscript.arguments(0))
  myfile.Delete
 End If

 Set wshell = CreateObject("WScript.Shell")
 Number = 0
 Do
  bWindowFound = wshell.AppActivate("Save as")
  wscript.sleep 500
  Number = Number + 1
  If bWindowFound Or Number > 10 Then Exit Do
 Loop
 If bWindowFound Then
  wshell.AppActivate "Save as"
  wscript.sleep 500
  wshell.SendKeys "%n" 'Could be a different letter as a hotkey for you.
  wscript.sleep 500
  wshell.SendKeys wscript.arguments(0) 
  wscript.sleep 500
  wshell.SendKeys "%s" 'Could be a different letter as a hotkey for you.
  wscript.sleep 500
 end If
end if

Regards, ScriptMan

Upvotes: 1

Related Questions