Python implementation adds Excel data to MongoDB

Source: Internet
Author: User
Tags mongoclient

Connecting a database with a Pymongo package

Use the XLRD package to read Excel data, and to convert Excel format data to JSON-formatted data due to different data structures

"TypeError: ' str ' object does not a support item assignment" due to a coding problem

To decode data using the Json.loads method

 #coding =utf-8import xlrdimport sysimport  jsonimport pymongofrom pymongo import mongoclient# Connection Database client=mongoclient (' localhost ', 27017) db=client.scrapyaccount=db.weibodata=xlrd.open_workbook (' test.xlsx ') table=data.sheets () [0]# Read the first line of data in Excel as a field name 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]) 


Python implementation adds Excel data to MongoDB

Related Article

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.