2016-07-28 23 views
0

我有一个python代码写入加载excel工作簿,遍历指定列中的所有行,将行保存在字典中并将该字典写入.txt文件。迭代通过以前过滤的行openpyxl

被引用的vb脚本会在openpyxl执行之前打开工作簿并对其进行过滤以仅显示一些数据。

唯一的问题是,当openpyxl遍历工作簿时,它会记录每个值而不是过滤的数据。

例如,如果原始电子表格是:

A B C 
1 x x x 
2 x y x 
3 x x x 

和I栏B滤光器,仅显示包含“X”的行,然后保存工作簿。我想openpyxl只能通过行1和3

遍历这里是我的代码:

from openpyxl import load_workbook 
from openpyxl import workbook 
import os 
#sort using vba script 
os.system(r"C:\script.vbs") 

#load workbook 
path = 'C:/public/temp/workbook.xlsm' 
wb = load_workbook(filename = path) 
ws=wb.get_sheet_by_name('Sheet3') 
#make empty lists 
proj_name = [] 
proj_num = [] 
proj_status = [] 

#iterate through rows and append values to lists 
for row in ws.iter_rows('D{}:D{}'.format(ws.min_row,ws.max_row)): 
    for cell in row: 
     proj_name.append(cell.value) 

for row in ws.iter_rows('R{}:R{}'.format(ws.min_row,ws.max_row)): 
    for cell in row: 
     proj_num.append(cell.value) 

for row in ws.iter_rows('G{}:G{}'.format(ws.min_row,ws.max_row)): 
    for cell in row: 
     proj_status.append(cell.value) 

#create dictionary from lists using defaultdict 
from collections import defaultdict 

dict1 = dict((z[0],list(z[1:])) for z in zip(proj_num,proj_name,proj_status)) 

with open(r"C:\public\list2.txt", "w") as text_file: 
    text_file.write(str(dict1)) 
    text_file.close() 
+0

openpyxl与文件格式的作品,作品VBA与Excel的应用程序:这些都是不一样的东西。你需要为openpyxl编写你自己的过滤器。循环遍历工作表多次也是非常低效的。 –

回答

1

可惜openpyxl目前不包括在其功能的过滤。正如the documentation笔记所述:“筛选器和排序只能由openpyxl配置,但需要在Excel等应用程序中应用。”

看起来好像你可能必须找到另一种解决办法...

+0

这是不幸的,谢谢你的回应,但! –