欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python如何實(shí)現(xiàn)excel數(shù)據(jù)添加到mongodb

 更新時(shí)間:2015年07月30日 16:39:02   作者:wojiaohuhu  
本文介紹了python是如何實(shí)現(xiàn)excel數(shù)據(jù)添加到mongodb,為了將數(shù)據(jù)導(dǎo)入mongodb,引入了pymongo,xlrd包,需要的朋友可以參考下

利用pymongo包進(jìn)行數(shù)據(jù)庫的連接,使用xlrd包讀取excel數(shù)據(jù),由于二者數(shù)據(jù)結(jié)構(gòu)的不同,要將excel格式數(shù)據(jù)轉(zhuǎn)換為json格式數(shù)據(jù)。由于編碼問題會(huì)出現(xiàn)“TypeError: 'str' object does not support item assignment”,要利用json.loads方法對數(shù)據(jù)進(jìn)行解碼

分享代碼如下

#coding=utf-8
 
import xlrd
import sys
import json
import pymongo
from pymongo import MongoClient
 
#連接數(shù)據(jù)庫
client=MongoClient('localhost',27017)
db=client.scrapy
account=db.weibo
 
data=xlrd.open_workbook('test.xlsx')
table=data.sheets()[0]
#讀取excel第一行數(shù)據(jù)作為存入mongodb的字段名
rowstag=table.row_values(0)
nrows=table.nrows
#ncols=table.ncols
#print rows
returnData={}
for i in range(1,nrows):
  #將字段名和excel數(shù)據(jù)存儲(chǔ)為字典形式,并轉(zhuǎn)換為json格式
  returnData[i]=json.dumps(dict(zip(rowstag,table.row_values(i))))
  #通過編解碼還原數(shù)據(jù)
  returnData[i]=json.loads(returnData[i])
  #print returnData[i]
  account.insert(returnData[i])

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論