Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

Python - Why does iSlice and OrderedDict not write all contents of MS Excel to JSON?

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...