![](/img/trans.png)
[英]Using Python (and DataNitro) to copy cells from a particular sheet in one Excel workbook, to a particular sheet in another Excel workbook
[英]Creating dictionary from excel workbook in python using sheet names as key
我的工作簿中有多個Excel工作表,它們的名稱類似於sheet1,sheet2,sheet3,並且我正在使用標題作為鍵將每個工作表中的數據轉換為字典。 但是現在我想創建一個嵌套的字典,在其中添加工作表名稱作為上述每個字典的鍵。 我的表有多個這種形式的工作表:Sheet1
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'}},
]
我在將工作表名稱添加為工作簿中多個工作表的鍵時遇到問題。
任何幫助將不勝感激。
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)
此代碼遍歷每個工作表,並在sheet_name后面附加“ full_dict”,然后是您為每個工作表返回的代碼。 參考“ 如何使用xlrd在Python中獲取Excel工作表名稱 ”完成名稱的獲取
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.