Python:使用 Win32 COM Api 打开 Excel 工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39877278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:51:26  来源:igfitidea点击:

Python: Open Excel Workbook using Win32 COM Api

pythonexcelwinapicom-interface

提问by tim

I'm using the following code to open and display a workbook within Excel:

我正在使用以下代码在 Excel 中打开和显示工作簿:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open('my_sheet.xlsm')
ws = wb.Worksheets('blaaaa') 
excel.Visible = True

When the File 'my_sheet.xlsm' is already opened, Excel asks me whether I want to re-open it without saving.

当文件“my_sheet.xlsm”已打开时,Excel 会询问我是否要在不保存的情况下重新打开它。

How could I check in advance whether the workbook is already opened up and in case it is, just bring it to the front?

我怎么能提前检查工作簿是否已经打开,如果已经打开,就把它放在前面?

EDIT: Found out by now:

编辑:现在发现:

if excel.Workbooks.Count > 0:
    for i in range(1, excel.Workbooks.Count+1):
        if excel.Workbooks.Item(i).Name is 'my_sheet.xlsm':
            wb = excel.Workbooks.Item(i)
            break

And one more question: My worksheet contains some headers where I enabled some filtering. So when the filters are set, and when I open the Workbook from Python, it sometimes asks me to enter a unique name to save the filter. Why is that? This is the dialogue:

还有一个问题:我的工作表包含一些标题,我在其中启用了一些过滤。所以当设置过滤器时,当我从 Python 打开工作簿时,它有时会要求我输入一个唯一的名称来保存过滤器。这是为什么?这是对话:

enter image description here

在此处输入图片说明

EDITOk here it says (in german language) that the latter problem is a known bug in 2007 and 2010 files: https://social.msdn.microsoft.com/Forums/de-DE/3dce9f06-2262-4e22-a8ff-5c0d83166e73/excel-api-interne-namenand it seems to exist if you open Excel-Files programmatically. Don't know whether there is a workaround.

编辑好的在这里它说(用德语)后一个问题是 2007 和 2010 文件中的一个已知错误:https: //social.msdn.microsoft.com/Forums/de-DE/3dce9f06-2262-4e22-a8ff- 5c0d83166e73/excel-api-interne-namen,如果您以编程方式打开 Excel 文件,它似乎存在。不知道有没有解决办法。

回答by Parfait

While you found a solution, consider using try/except/finallyblock. Currently your code will leave the Excel.exe process running in background (check Task Manager if using Windows) even if you close the visible worksheet. As an aside, in Python or any other language like VBA, any external API such as this COM interface should always be released cleanly during application code.

当您找到解决方案时,请考虑使用try/except/finally块。目前,即使您关闭了可见的工作表,您的代码也会让 Excel.exe 进程在后台运行(如果使用 Windows,请检查任务管理器)。顺便说一句,在 Python 或任何其他语言(如 VBA)中,应始终在应用程序代码期间干净地发布任何外部 API(如此 COM 接口)。

Below solution uses a defined function, openWorkbook()to go two potential routes: 1) first attempts to relaunch specified workbook assuming it is opened and 2) if it is not currently opened launches a new workbook object of that location. The last nested try/exceptis used in case the Workbooks.Open()method fails such as incorrect file name.

下面的解决方案使用定义的函数,openWorkbook()走两条可能的路线:1)首先尝试重新启动指定的工作簿,假设它已打开,2)如果当前未打开,则启动该位置的新工作簿对象。try/except如果Workbooks.Open()方法失败,例如文件名不正确,则使用最后一个嵌套。

import win32com.client as win32

def openWorkbook(xlapp, xlfile):
    try:        
        xlwb = xlapp.Workbooks(xlfile)            
    except Exception as e:
        try:
            xlwb = xlapp.Workbooks.Open(xlfile)
        except Exception as e:
            print(e)
            xlwb = None                    
    return(xlwb)

try:
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = openWorkbook(excel, 'my_sheet.xlsm')
    ws = wb.Worksheets('blaaaa') 
    excel.Visible = True

except Exception as e:
    print(e)

finally:
    # RELEASES RESOURCES
    ws = None
    wb = None
    excel = None