How Python implements Excel data to be added to MongoDB

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

  • 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.