Range类的AutoFilter方法失败(Dispatch vs EnsureDispatch)

此代码失败,错误:“范围类的自动过滤方法失败”

from win32com.client.gencache import EnsureDispatch excel = EnsureDispatch('Excel.Application') excel.Visible = 1 workbook = excel.Workbooks.Add() sheet = workbook.ActiveSheet sheet.Cells(1, 1).Value = 'Hello world' sheet.Columns.AutoFilter() 

该代码也失败,虽然它曾经工作:

 from win32com.client import Dispatch excel = Dispatch('Excel.Application') excel.Visible = 1 workbook = excel.Workbooks.Add() sheet = excel.ActiveSheet sheet.Cells(1, 1).Value = 'Hello world' sheet.Columns.AutoFilter() 

Python使用win32com直接与Windows应用程序通信,并且可以使用(通过EnsureDispatch )或不使用(通过Dispatch )事先知道应用程序的API。 当您调用EnsureDispatch时,API被提取并写入win32com.gen_py。 ,从而永久地将应用程序的API添加到您的Python库中。

一旦您使用EnsureDispatch初始化应用程序,任何时候脚本使用该应用程序的Dispatch ,它将被给予预先获取的API。 这很好,因为可以使用预定义的应用程序常量( 来自win32com.client import常量 )。

但是,有时以前工作的代码将会中断。 例如,在下面的代码中,只要Excel API以前从未caching在库中, AutoFilter()将无参数运行。

 # ExcelAutoFilterTest1 # Works unless you ever previously called EnsureDispatch('Excel.Application') from win32com.client import Dispatch excel = Dispatch('Excel.Application') excel.Visible = 1 workbook = excel.Workbooks.Add() sheet = workbook.ActiveSheet sheet.Cells(1, 1).Value = 'Hello world' sheet.Columns.AutoFilter() 

以下代码将总是失败,因为现在Excel API已经被提取并写入到您的Python库中的win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x7 ,它将不再接受不带参数的AutoFilter()

 # ExcelAutoFilterTest2 # Always fails with error: AutoFilter method of Range class failed from win32com.client.gencache import EnsureDispatch excel = EnsureDispatch('Excel.Application') excel.Visible = 1 workbook = excel.Workbooks.Add() sheet = workbook.ActiveSheet sheet.Cells(1, 1).Value = 'Hello world' sheet.Columns.AutoFilter() 

下面的代码总是起作用,因为我们现在提供了VisibleDropDown参数(1 = on,0 = off)。

 # ExcelAutoFilterTest3 # Always succeeds from win32com.client.gencache import EnsureDispatch excel = EnsureDispatch('Excel.Application') excel.Visible = 1 workbook = excel.Workbooks.Add() sheet = workbook.ActiveSheet sheet.Cells(1, 1).Value = 'Hello world' sheet.Columns.AutoFilter(1) 

这似乎是一个错误,因为Excel API文档声明所有参数为AutoFilter是可选的:

“如果你省略了所有的参数,这个方法只是切换指定范围内的AutoFilter下拉箭头的显示。