2017-06-26 43 views
0

我在工作簿中有多個表格,名稱爲sheet1,sheet2,sheet3,我將每張表格中的數據轉換爲使用標題作爲關鍵字的字典。但是現在我想創建一個嵌套的字典,我添加表單名稱作爲上述每個字典的關鍵字。我的表有這種形式的多張: 工作表Sheet1使用表格名稱作爲關鍵字在Excel中創建字典

IP Address  prof  type 
xx.xx.xx  abc  xyz 
xx.xx.xx  efg  ijk 

Sheet2中

IP Address  prof  type 
xx.xx.xx  abc  xyz 
xx.xx.xx  efg  ijk 

現在我試圖像這樣:

from xlrd import open_workbook 

book = open_workbook('workbook.xls') 
sheet = book.sheet_by_index(0) 
sheet_names = book.sheet_names() 

# reading header values 
keys = [sheet.cell(0, col_index).value for col_index in range(sheet.ncols)] 

dict_list = [] 
for row_index in range(1, sheet.nrows): 
    d = {keys[col_index]: sheet.cell(row_index, col_index).value 
     for col_index in range(sheet.ncols)} 
    dict_list.append(d) 

print (dict_list) 

它打印此:

[{'IP Address': 'xx.xx.xx', 'prof': 'abc', 'type': 'xyz'}, {'IP Address': 
'xx.xx.xx', 'prof': 'efg', 'type': 'ijk'}] 

what I need is : 
    [{'Sheet1':{'IP Address': 'xx.xx.xx', 'prof': 'abc', 'type': 'xyz'}, {'IP 
    Address': 'xx.xx.xx', 'prof': 'efg', 'type': 'ijk'}}, 
    {'Sheet2':{'IP Address': 'xx.xx.xx', 'prof': 'abc', 'type': 'xyz'}, {'IP 
     Address': 'xx.xx.xx', 'prof': 'efg', 'type': 'ijk'}}, 
     ] 

我有問題ems將工作表名稱添加爲工作簿中多個工作表的關鍵字。

任何幫助將不勝感激。

回答

0
from xlrd import open_workbook 

book = open_workbook('Workbook1.xlsx') 
pointSheets = book.sheet_names() 
full_dict = {} 
for i in pointSheets: 
    # reading header values 
    sheet = book.sheet_by_name(i) 
    keys = [sheet.cell(0, col_index).value for col_index in range(sheet.ncols)] 

    dict_list = [] 
    for row_index in range(1, sheet.nrows): 
     d = {keys[col_index]: sheet.cell(row_index, col_index).value 
      for col_index in range(sheet.ncols)} 
     dict_list.append(d) 
    full_dict[i] = dict_list 
    dict_list = {} 

print (full_dict) 

此代碼在每張工作表上迭代並追加到'full_dict'工作表名,然後是您的代碼已經爲每個工作表返回的內容。 收購的名字是參考「How to get excel sheet name in Python using xlrd

+0

非常感謝。完美的作品! – user12083

相關問題