Using the Pymongo package for database connection, use XLRD package to read Excel data, because of the different data structure, to convert Excel format data into JSON format data. The encoding problem occurs because "TypeError: ' str ' object does not the support item assignment" to decode the data using the Json.loads method
Share the code below
#coding =utf-8 Import xlrdimport sysimport jsonimport pymongofrom pymongo import mongoclient #连接数据库client =mongoclient (' localhost ', 27017) Db=client.scrapyaccount=db.weibo data=xlrd.open_workbook (' test.xlsx ') table=data.sheets () [0]# Read the first line of data in Excel as a field name to be stored in MongoDB rowstag=table.row_values (0) Nrows=table.nrows#ncols=table.ncols#print rowsreturndata= {}for I in range (1,nrows): #将字段名和excel数据存储为字典形式 and converted to JSON format returndata[i]=json.dumps (dict (Zip (Rowstag, Table.row_values (i))) #通过编解码还原数据 returndata[i]=json.loads (returndata[i]) #print Returndata[i] Account.insert (Returndata[i])
The above is the whole content of this article, I hope that everyone's study has helped.