I'm writing the contents of Excel into JSON.
I have 3 columns in Excel: Items, Quantity and Price.
It have 15 rows of data. With this code, it only writes the last row of Excel into JSON.
What's the issue here ?
import json
from collections import OrderedDict
from itertools import islice
import openpyxl
# Open the workbook and select a worksheet
wb=openpyxl.load_workbook("C:\Users\Ricky\Desktop\NewStock.xlsx")
sheet = wb['ItemList']
# List to hold dictionaries
MyItem_list = []
# Iterate through each row in worksheet and fetch values into dict
myitems = OrderedDict()
for row in islice(sheet.values, 1, sheet.max_row+1):
myitems['Item'] = row[0]
myitems['Quantity'] = row[1]
myitems['Price'] = row[2]
MyItem_list.append(myitems)
print(MyItem_list)
# Serialize the list of dicts to JSON ... creates a json string
j = json.dumps(myitems)
print(type(j)) #j is of string object
# Write to file
with open('C:\Users\Ricky\Desktop\dataitem.json', 'wt') as f:
f.write(j)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…