openpyxl从excel中提取值并存储在键值对中

已经编写了一个python脚本来获取单元格值并逐行显示在列表中。

这是我的脚本:

book = openpyxl.load_workbook(excel_file_name) active = book.get_sheet_by_name(excel_file_name) def iter_rows(active): for row in active.iter_rows(): yield [cell.value for cell in row] res = list(iter_rows(active)) for new in res: print new 

上述脚本的输出:[state,country,code] [abc,xyz,0] [def,lmn,0]

我想输出在以下格式:[状态:abc,国家:xyz,代码:0] [状态:def,国家:lmn,代码:0]

请注意:我想从openpyxl做到这一点

尝试这个:

 res = iter_rows(active) keys = next(res) for new in res: print dict(zip(keys, new)) 

res是一个迭代器。 因此, next(res)给出下一个元素。 在我们的情况下,字典的关键。 用for循环遍历其余的resdict()为所有字典中使用相同keys每个元素创build一个新的字典。 函数zip()以这种方式组合了两个(或更多)序列,它创build了每个序列中具有一个元素的对。 dict()将这些对中的一个用作一个新项目的键和值,并通过所有的对。 例如,这个:

 dict(zip('abc', [1, 2, 3])) 

结果在这本词典里:

 {'a': 1, 'b': 2, 'c': 3}