python - Range 类的 AutoFilter 方法失败(Dispatch 与 EnsureDispatch)

标签 python excel python-2.7 win32com autofilter

此代码失败并出现错误:“Range 类的 AutoFilter 方法失败”

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。这很好,因为您随后可以使用预定义的应用程序常量(from win32com.client import constants)。

但是,有时以前工作的代码会被破坏。例如,在下面的代码中,只要 Excel API 以前从未缓存在库中,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 documentation声称 AutoFilter 的所有参数都是可选的:

"If you omit all the arguments, this method simply toggles the display of the AutoFilter drop-down arrows in the specified range."

关于python - Range 类的 AutoFilter 方法失败(Dispatch 与 EnsureDispatch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22930751/

相关文章:

python - 在流式 hadoop 程序中获取输入文件名

python - 如何安装 paramiko 模块?

python - 我可以从另一个字节对象中获取长度为 1 的字节对象,而不进行切片吗?

python - 在运行时修改循环函数的内部

python - 如何知道安装的pylab版本?

excel - 使用函数解析 Excel 中的数据

excel - VBA。使用动态最后一列调整表格大小

vba - 总和范围直到某个单元格颜色或值之后?

python - 类型错误不可散列类型 :set

python-2.7 - Pandas 数据框最长系列,数据不间断