Python:使用Win32 COM Api打开Excel工作簿 [英] Python: Open Excel Workbook using Win32 COM Api

查看:655
本文介绍了Python:使用Win32 COM Api打开Excel工作簿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the following code to open and display a workbook within 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

当文件'my_sheet.xlsm'已经打开时,Excel询问我是否要不保存就重新打开它.

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

我如何预先检查工作簿是否已经打开,如果要打开,将其放在最前面?

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

编辑:现已发现:

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

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

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:

编辑好,在这里它说(德语),后一个问题是2007年和2010年文件中的已知错误:

EDIT Ok 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-namen and it seems to exist if you open Excel-Files programmatically. Don't know whether there is a workaround.

推荐答案

找到解决方案的同时,请考虑使用

While you found a solution, consider using try/except/finally block. 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.

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

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/except is used in case the Workbooks.Open() method fails such as incorrect file name.

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

这篇关于Python:使用Win32 COM Api打开Excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆