python如何实现excel数据添加到mongodb
作者:wojiaohuhu 时间:2023-05-05 17:23:18
利用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])
标签:python,mongodb
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈python字典多键值及重复键值的使用
2022-08-12 03:50:29
![](https://img.aspxhome.com/file/2023/5/105195_0s.jpg)
python numpy 常用随机数的产生方法的实现
2021-06-14 22:44:05
五个Python命令使用的小妙招分享
2023-12-09 07:58:04
![](https://img.aspxhome.com/file/2023/5/127145_0s.png)
详解Vue 换肤方案验证
2024-05-21 10:17:31
![](https://img.aspxhome.com/file/2023/4/125284_0s.gif)
实现div可编辑的常见方法
2007-11-06 12:02:00
MySQL日期数据类型、时间类型使用总结
2024-01-27 09:46:51
go学习笔记读取consul配置文件详解
2024-05-09 10:08:14
![](https://img.aspxhome.com/file/2023/8/127038_0s.png)
机器深度学习二分类电影的情感问题
2022-07-17 06:13:28
![](https://img.aspxhome.com/file/2023/1/72851_0s.png)
Python实现的爬取豆瓣电影信息功能案例
2023-07-18 21:59:25
![](https://img.aspxhome.com/file/2023/2/60742_0s.png)
Python如何实现感知器的逻辑电路
2021-01-09 00:41:38
![](https://img.aspxhome.com/file/2023/5/91975_0s.png)
mysql 存在该记录则更新,不存在则插入记录的sql
2024-01-29 07:19:24
如何把Mysql卸载干净(亲测有效)
2024-01-16 09:06:06
![](https://img.aspxhome.com/file/2023/7/70457_0s.jpg)
Python协程 yield与协程greenlet简单用法示例
2023-02-23 04:07:25
Python利用docx模块实现快速操作word文件
2022-06-19 07:18:45
![](https://img.aspxhome.com/file/2023/8/78538_0s.png)
python Tkinter版学生管理系统
2021-03-11 11:07:48
![](https://img.aspxhome.com/file/2023/9/75379_0s.jpg)
Python之根据输入参数计算结果案例讲解
2022-08-27 07:44:50
![](https://img.aspxhome.com/file/2023/9/69499_0s.jpg)
Python实现井字棋小游戏
2023-04-27 05:29:07
![](https://img.aspxhome.com/file/2023/0/76700_0s.jpg)
Windows下nodejs安装及环境配置的实战步骤
2024-05-03 15:36:22
![](https://img.aspxhome.com/file/2023/9/129499_0s.png)
opencv用VS2013调试时用Image Watch插件查看图片
2022-04-20 14:49:12
![](https://img.aspxhome.com/file/2023/9/90369_0s.png)
php设计模式之适配器模式实例分析【星际争霸游戏案例】
2024-05-11 09:55:05