from openpyxl import *
Variable_Model_Path=defaultdict(list)
Sheet_Name=wb.get_sheet_by_name(Sheet)
for row in Sheet_Name.iter_rows():
Row=[cell.value for cell in row]
for cell_ind,cell in enumerate(Row):
print cell
以上是我的示例代码。
我有一张excel表,其中包含标题var1,var2,var3。我想创建一个字典{Var1:1,4,7,10}其中Var1将是标题名称,值将是相应的列值。我正在使用openpyxl模块。用户可以给出变量名称和值,它们将是动态的。
Var1 Var2 Var3
答案 0 :(得分:2)
这:
from openpyxl import *
from collections import defaultdict
path = "/Users/romain/Desktop/Classeur2.xlsx"
Sheet = "Feuil1"
wb = load_workbook(path)
Variable_Model_Path = defaultdict(list)
Sheet_Name = wb.get_sheet_by_name(Sheet)
keys = False
for row in Sheet_Name.iter_rows():
if not keys:
keys = [cell.value for cell in row]
continue
Row=[cell.value for cell in row]
for cell_ind,cell in enumerate(Row):
Variable_Model_Path[keys[cell_ind]].append( cell)
给了我:
Variable_Model_Path
defaultdict(list,
{u'var 1': [1L, 4L, 7L],
u'var 2': [2L, 5L, 8L],
u'var 3': [3L, 6L, 9L]})