Home > Backend Development > Python Tutorial > python如何实现excel数据添加到mongodb

python如何实现excel数据添加到mongodb

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-10 15:08:25
Original
1684 people have browsed it

利用pymongo包进行数据库的连接,使用xlrd包读取excel数据,由于二者数据结构的不同,要将excel格式数据转换为json格式数据。由于编码问题会出现“TypeError: 'str' object does not support item assignment”,要利用json.loads方法对数据进行解码

分享代码如下

#coding=utf-8
 
import xlrd
import sys
import json
import pymongo
from pymongo import MongoClient
 
#连接数据库
client=MongoClient('localhost',27017)
db=client.scrapy
account=db.weibo
 
data=xlrd.open_workbook('test.xlsx')
table=data.sheets()[0]
#读取excel第一行数据作为存入mongodb的字段名
rowstag=table.row_values(0)
nrows=table.nrows
#ncols=table.ncols
#print rows
returnData={}
for i in range(1,nrows):
  #将字段名和excel数据存储为字典形式,并转换为json格式
  returnData[i]=json.dumps(dict(zip(rowstag,table.row_values(i))))
  #通过编解码还原数据
  returnData[i]=json.loads(returnData[i])
  #print returnData[i]
  account.insert(returnData[i])
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template