利用pymongo包進(jìn)行數(shù)據(jù)庫(kù)的連接,使用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方法對(duì)數(shù)據(jù)進(jìn)行解碼
分享代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#coding=utf-8 import xlrd import sys import json import pymongo from pymongo import MongoClient #連接數(shù)據(jù)庫(kù) 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]) |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。