0
我想遍歷Excel工作表中的所有行,並將每行(從第2行開始)的值存儲在1大列表中的各個字典中。在Openpyxl中使用嵌套字典創建列表
我有一個Excel項目從A柱橫跨的簡單列表 - 列d:
Fruit: Quantity: Color: Cost
Apple 5 Red 0.6
Banana 6 Yellow 0.4
Orange 4 Orange 0.3
Kiwi 2 Green 0.1
我想看看的第一個結果是這樣的:
[{'Fruit': 'Apple', 'Quantity': 5, 'Color': 'Red', 'Cost': 0.6}]
下面是我的代碼看看此刻:
import openpyxl
wb = openpyxl.load_workbook('fruit.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
for row in range(2, sheet.max_row + 1):
fruit = sheet['A' + str(row)].value
quantity = sheet['B' + str(row)].value
color = sheet['C' + str(row)].value
cost = sheet['D' + str(row)].value
allFruits = [{'Fruit': fruit,
'Quantity': quantity,
'Color': color,
'Cost': cost}]
print(allFruits)
當我運行代碼時,結果只打印最後一個活動行在表:
[{'Fruit': 'Kiwi', 'Quantity': 2, 'Color': 'Green', 'Cost': 0.1}]
我想這種格式ALL行,而不僅僅是最後一行。我不明白爲什麼代碼跳過其中的所有行,只是打印最後一行。誰能幫忙?
這完美的作品,非常感謝。 –