Python- 如何在 Excel 自动筛选器中显示选择

Python- How to show the selections in an Excel AutoFilter

这可能是一项简单的任务,但对于我来说,我无法找到解决方案。我有一个 excel 文档,其中有一个 table。此 table 中的列都应用了自动筛选器。我想要做的就是能够 select 该自动过滤器中的所有条目(对于第 9 列)并将其存储在一个数组中。我正在使用 Win32Com。

import win32com.client as win32

working_dir = 'C:\invoice\'
save_dir = 'C:\test\'

xl = win32.gencache.EnsureDispatch("Excel.Application")
xl.Visible = True

template_wb = xl.Workbooks.Open(working_dir + 'Settlement report V6-EMPLATE.xlsm')

#Worksheets
orgdata_ws = template_wb.Sheets('Organization Data')
masterdata_ws = template_wb.Sheets('Master Data')

#I want to access the autofilter in column 9 and simply get the contents in the autofilter list and put them in the array
filtercontents = []
thefilter = orgdata_ws.Columns(9).Autofilter
for i in thefilter:
    filtercontents.append(i)     ?????????

我记得我的第一个剧本....

你嫁给 win32 了吗?

https://mail.python.org/pipermail/python-list/2011-October/613213.html

Python - How to turn-on Excel Auto Filter on cells in non-first row?

您正在尝试迭代方法引用 Autofilter,而不是它的 return 值 Autofilter()。通过添加括号,您可以调用该方法。没有括号,您只是对该方法的引用。

我为感兴趣的人弄清楚了。原来我想访问的列被引用以及数据透视表 Table 中的数据透视表字段。因此,一旦我能够读取该数据透视字段的内容,我就可以将其汇集到一个数组中(然后使用该数组打印出 pdf 发票)。有一些编码问题,但使用 setdefaultcoding 函数解决了这个问题。这是代码:

import win32com.client as win32
import sys

reload(sys)
sys.setdefaultencoding("UTF-8")

working_dir = 'C:\invoice\'
save_dir = 'C:\test\'

xl = win32.gencache.EnsureDispatch("Excel.Application")
xl.Visible = True

template_wb = xl.Workbooks.Open(working_dir + 'Settlement report V6- TEMPLATE.xlsm')

#Worksheets
settlements_ws = template_wb.Sheets('Settlement')
orgdata_ws = template_wb.Sheets('Organization Data')
masterdata_ws = template_wb.Sheets('Master Data')

settlements_ws.Activate()

agencies = []

def maxrow(sheet):
    used = sheet.UsedRange
    nrows = used.Row + used.Rows.Count - 1
    return nrows

mypivot = settlements_ws.PivotTables("PivotTable2").PivotFields("AgencyName")

for j in mypivot.PivotItems():
    j = str(j)
    if j == "#N/A":
        continue
    else:
        j = j.replace("\xc2\xa0","")
        agencies.append(j)
print agencies

#Looping through agencies and saving PDFs
for i in agencies:
    settlements_ws.Cells(8,3).Value = i
    print settlements_ws.Cells(8,3).Value
    settlements_ws.ExportAsFixedFormat(0, save_dir + i + '.pdf')

print "Finished!"