Python如何在Excel AutoFi中显示选择

2024-09-27 07:17:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是一个简单的任务,但就我的一生而言,我找不到解决办法。我有一个有表格的excel文档。此表中的所有列都应用了自动筛选。我所要做的就是能够选择自动筛选(第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)     ?????????

Tags: andtheindatawsdirtemplateworking
3条回答

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

我为感兴趣的人找到了答案。结果我想访问的列被引用了,同时也引用了Pivot表中的Pivot字段。因此,一旦我能够读取pivotfield的内容,我就可以将其放入一个数组中(然后使用该数组打印出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!"

相关问题 更多 >

    热门问题