How does python add excel Data to mongodb?

Source: Internet
Author: User
Tags mongoclient
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.