使用Python脚本从SAP导出Excel文件

2024-09-28 22:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我将SAP GUI脚本(最初是VB)改编为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()

然后我无法控制“另存为”窗口,SAP GUI脚本无法检测到这一点,我的所有测试也无法运行

我在这里发现了2019年的类似问题,但没有答案或解决方案:Exporting with SAP using Python


Tags: thetextdfsessionusrwithlistlow
1条回答
网友
1楼 · 发布于 2024-09-28 22:19:20

假设文件类型为xlsx。在本例中,我使用了以下解决方法:

...
#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

你好,编剧

相关问题 更多 >