我正在创建Windows自动化脚本。我需要将Excel应用程序置于前台。我能够打开excel应用程序并获取正在运行的子进程的列表。但是我不确定如何将Excel应用程序应用到前台。请帮助
import subprocess
from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
xl.Visible = True
cmd = 'WMIC PROCESS get Caption,Commandline,Processid'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
print(line)
我正在打开应用程序列表,但是我需要将Excel置于前台。请帮我怎么做。
b'EXCEL.EXE“ C:\ Program Files \ Microsoft Office \ root \ Office16 \ EXCEL.EXE”
b'SearchFilterHost.exe 740 \ r \ r \ n' b'python.exe C:\ Users \ arvin \ AppData \ Local \ Programs \ Python \ Python37-32 \ python.exe \ r \ r \ n' b'conhost.exe \ ?? \ C:\ WINDOWS \ system32 \ conhost.exe 0x4 15724 \ r \ r \ n' b'cmd.exe C:\ WINDOWS \ system32 \ cmd.exe / c“ WMIC过程获取标题,命令行,Processid” 18084 \ r \ r \ n'
答案 0 :(得分:3)
如果您正在使用所有Microsoft Office应用程序,则 object.Activate()方法将起作用。这是Microsoft VBA和C#应用程序调用的一部分,也可用于第三方语言。下面的代码在Windows 10环境,带有pywin32的python 3.7和MS-Office 2013上进行了测试。
####### Activate one excel file ##############
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb1 = excel.Workbooks.Open(r'C:\python\so\sheet1.xlsx')
wb2 = excel.Workbooks.Open(r'C:\python\so\sheet2.xlsx')
wb3 = excel.Workbooks.Open(r'C:\python\so\sheet3.xlsx')
excel.Visible = True
# This will open 3 workbooks with wb1 on top.
excel.Application.ActiveWorkbook.Name
# Prints name of currently active workbook, i.e., the one on top.
wb3.Activate() # puts workbook3 on top
wb2.Activate() # puts workbook2 on top
### You may need to install pywin32.
### pip install pywin32
答案 1 :(得分:2)
如果您确实需要将excel窗口置于前台,则可以执行以下操作:
from win32com.client import Dispatch
from win32gui import SetForegroundWindow
xl = Dispatch("Excel.Application")
xl.Visible = True
SetForegroundWindow(xl.hwnd)
其中hwnd是Excel的窗口ID。 More information about hwnd