This article describes how to add excel Data to mongodb using python. To import data to mongodb, we have introduced the pymongo and xlrd packages. For more information, see the pymongo package, use the xlrd package to read excel Data. Because of the different data structures, convert the excel format data to json format data. Due to Encoding Problems, "TypeError: 'str' object does not support item assignment" may occur. You must use the json. loads method to decode the data.
The sharing code is as follows:
# Coding = UTF-8 import xlrdimport sysimport jsonimport pymongofrom pymongo import MongoClient # connect to the database client = MongoClient ('localhost', 27017) db = client. scrapyaccount = db. weibo data‑xlrd.open_workbook('test.xlsx') table = data. sheets () [0] # Read the first row of data in excel as the field name rowstag = table in mongodb. row_values (0) nrows = table. nrows # ncols = table. ncols # print rowsreturnData ={} for I in range (1, nrows): # store the field name and excel Data as dictionaries and convert them to the json format returnData [I] = json. dumps (dict (zip (rowstag, table. row_values (I) # Use CODEC to restore Data returnData [I] = json. loads (returnData [I]) # print returnData [I] account. insert (returnData [I])
The above is all the content of this article, hoping to help you learn.