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行,而不仅仅是最后一行。我不明白为什么代码跳过其中的所有行,只是打印最后一行。谁能帮忙?
这完美的作品,非常感谢。 –