Python win32com聚焦或打开Excel文件

发布于 2025-02-01 09:17:48 字数 437 浏览 0 评论 0原文

我正在尝试使用win32com.client专注于Excel文件。

我想要的是:

(1)当已经打开给定的Excel文件时,只需返回工作簿实例即可。

(2)如果该Excel文件尚未打开>>打开Excel文件,然后返回工作簿实例。

我之所以挣扎,是因为我不知道方法getActiveObject和amp;派遣等...

在许多情况下,发生错误>> (-2147352567 .......

谁能制作我想要的代码?

这是我代码的一部分

'''
import win32com.client
xlsApp=win32com.client.GetActiveObject("Excel.Application")
myWB=xlsApp.Workbooks(workbook_name) 
'''

i am trying to focus to excel file using win32com.client.

what i want is:

(1) simply return workbook instance when a given excel file is already opened.

(2) if that excel file is not opened yet >> open the excel file and then return workbook instance.

i am struggling because i don't know the difference between the methods getactiveobject & dispatch and so on...

in many cases, an error occurs >> (-2147352567 .......

can anyone make the code that i want?

this is a part of my code

'''
import win32com.client
xlsApp=win32com.client.GetActiveObject("Excel.Application")
myWB=xlsApp.Workbooks(workbook_name) 
'''

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦醒时光 2025-02-08 09:17:48

在此之前,我已经做到了,这是我这样做的方式,

import pygetwindow as gw
import pywinauto

def focus_to_window(window_title=None): 
     window = gw.getWindowsWithTitle(window_title)[0] 
     if window.isActive == False: 
         try: 
             pywinauto.application.Application().connect(handle=window._hWnd).top_window().set_focus() 
         except: 
             print('No permission')

需要您传递窗口标题,而不必是确切的名称,例如,如果您的Discord名为Discord #general #general您只是只有需要放置discord,因为无论您去哪里discord字符串都将始终在那里也存在,

也将其打印无许可,因为某些应用程序需要它作为管理员运行

I've done this before this is how I did it

import pygetwindow as gw
import pywinauto

def focus_to_window(window_title=None): 
     window = gw.getWindowsWithTitle(window_title)[0] 
     if window.isActive == False: 
         try: 
             pywinauto.application.Application().connect(handle=window._hWnd).top_window().set_focus() 
         except: 
             print('No permission')

That function requires you to pass in a window title, it does not have to be exact name for example if you have Discord named Discord #general you just need to put Discord because no matter where you go Discord string will always be in there

Also the reason why it prints No permission because some applications requires it to run as Admin

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文