python读取excel写入mysql_使用Python读Excel数据Insert到MySQL
#!/usr/bin/env python
#coding:utf-8
import xlrd
import MySQLdb
import datetime
xlsfile=r'C:\Users\XUWU\Desktop\data.xlsx'
book = xlrd.open_workbook(xlsfile)
#获取sheet的数量
count = len(book.sheets())
#设置连接数据库
database = MySQLdb.connect(host='192.168.1.30',user='root',passwd='123456',db='crm')
#设置字符集
database.set_character_set('utf8')
cursor = database.cursor()
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
starttime = datetime.datetime.now()
print '开始时间:%s' % (starttime)
#循环sheet
for i in range(0,count-1):
sheet = book.sheet_by_index(i)
query = """INSERT INTO bill_test ( member_id, name, tel, phone, dq_datetime, address, parking) VALUES ( %s, %s, %s, %s, %s, %s, %s)"""
#循环每一行
for r in range(1, sheet.nrows):
#idseq = sheet.cell(r,0).value
member_id = sheet.cell(r,1).value
name = sheet.cell(r,2).value
tel = sheet.cell(r,3).value
phone = sheet.cell(r,4).value
#dq_datetime = sheet.cell(r,5).value
#读日期这里要处理一下,不然全变成数字了
dq_datetime_num=xlrd.xldate_as_tuple(sheet.cell(r,5).value,0)
dq_datetime = '%s/%s/%s' % (dq_datetime_num[0],dq_datetime_num[1],dq_datetime_num[2])
address = sheet.cell(r,6).value
parking = sheet.cell(r,7).value
values = (member_id, name, tel, phone, dq_datetime, address, parking)
#print query,values
cursor.execute(query, values)
cursor.close()
database.commit()
database.close()
endtime=datetime.datetime.now()
print '结束时间:%s' % (endtime)
print '用时:%s 秒' % (endtime-starttime)
CREATE TABLE `bill_test` (
`idseq` mediumint(10) unsigned NOT NULL AUTO_INCREMENT,
`member_id` int(10) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`tel` varchar(20) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`dq_datetime` varchar(20) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
`parking` varchar(200) DEFAULT NULL,
PRIMARY KEY (`idseq`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
使用Python从 MySQL写数据到Excel
#!/usr/bin/env python
#coding:utf-8
import xlwt
import MySQLdb
import datetime
database = MySQLdb.connect(host='192.168.1.30',user='root',passwd='123456',db='crm')
#设置字符集
database.set_character_set('utf8')
cursor = database.cursor()
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
starttime = datetime.datetime.now()
print '开始时间:%s' % (starttime)
#通过SQL得到该表有多少行,如果想取出指定的数据,只需要在后面加where条件即可。
sql2 = 'select count(*) from bill_test;';
cursor.execute(sql2)
count_rows=cursor.fetchone()[0]
wbk = xlwt.Workbook(encoding='utf-8',style_compression=0)
sheet = wbk.add_sheet('sheet 1', cell_overwrite_ok=True)
#设置写excel的样式
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = 'Times New Roman'
#0x0190设置字体为20,默认为0x00C8 字体为10 ,0x00C8为十六进制的数字
font.height = 0x0190
font.bold = True
style.font = font
#查询得到该表有多少列
query_colums="select count(*) from information_schema.COLUMNS where TABLE_SCHEMA='crm' and table_name='bill_test';"
cursor.execute(query_colums)
count_cols = cursor.fetchone()[0]
sql = 'select member_id, name, tel, phone, dq_datetime, address, parking from bill_test;'
cursor.execute(sql)
#定义所有的列名,共7列
columnName = ['账号','名称','电话','手机','到期日期','地址','园区名称']
#将列名插入表格,共7列
for i in range(len(columnName)):
sheet.write(0,i,columnName[i],style)
#通过循环取出每一行数据,写入excel
for i in range(1,count_rows-1):
data = cursor.fetchone()
for j in range(0,count_cols-1):
sheet.write(i,j,data[j],style)
cursor.close()
database.close()
wbk.save('C:\Users\XUWU\Desktop\data01.xls')
endtime=datetime.datetime.now()
print '结束时间:%s' % (endtime)
print '用时:%s 秒' % (endtime-starttime)
python之TXT数据导入数据库
为了导入数据,可以先对数据做些处理,让其更容易导入数据库
#!/usr/bin/python
#coding=utf-8
import _mysql,sys,time
#读入数据函数
def add_data(id,name,created_time):
try:
conn=_mysql.connect('127.0.0.1','root','')
conn.query("set names utf8")
conn.query("insert into mysql.test3(%s,%s,%s) values('%s','%s','%s')"%('object_id','object_name','created',id,name,created_time))
result=conn.use_result()
conn.close()
except _mysql.Error,e:
print ("error %d:%s" % (e.args[0],e.args[1]))
sys.exit(1)
if __name__ =="__main__":
f= open("/opt/testdata/aaa.txt","r")
time1=time.time()
print time.ctime()
#读出第一行数据,作为数据表的段名
line=f.readline()
content=line.strip().split(",")
conn0=_mysql.connect('127.0.0.1','root','')
print 'connection is builded succesfully'
conn0.query("drop table if exists mysql.test3")
conn0.query("create table mysql.test3(%s varchar(90),%s varchar(90),%s varchar(90))"%(content[0][1:-1],content[1][1:-1],content[2][1:-1]))
conn0.close()
#运用next函数,让for循环从第二行开始读数据
next(f)
for line in f:
#做一些处理,让每一段分开,放置在一个列表中
content=line.strip().split(",")
add_data(id=content[0][1:-1],name=content[1][1:-1],created_time=content[2][1:-1])
f.close()
time2=time.time()
print time.ctime()
#计算导入数据的时间
print 'importing time is %f'%(time2-time1)
python读取excel写入mysql_使用Python读Excel数据Insert到MySQL相关推荐
- pandas读取csv写入mysql_使用python的pandas库读取csv文件保存至mysql数据库
第一:pandas.read_csv读取本地csv文件为数据框形式 data=pd.read_csv('G:\data_operation\python_book\chapter5\\sales.cs ...
- python读取和写入excel里面的数据(附int变float解决方法)
python读取和写入excel里面的数据(附int变float解决方法) 参考文章: (1)python读取和写入excel里面的数据(附int变float解决方法) (2)https://www. ...
- Python读取和写入excel文件
Hello!今天我们来聊一下python读取和写入文件的操作. 在进行数据分析和数据挖掘等等有关数据的操作中,我们一般都会碰到python与excel的具体操作.从excel中读取数据出来进行分析,清 ...
- mac如何用python打开excel,Mac——利用Python读取与写入Excel文档
Mac--利用Python读取与写入Excel文档 目的:按照自定义的格式写入或读取Excel文档,如标红加粗等 Python代码: import xlwt import pandas as pd d ...
- python读取txt文件写入-python 读取、写入txt文件的示例
写入文件 使用open()函数和write()函数 但是有两种写法,分别是'a'和'w' 'a' 表示写入文件 若无该文件会直接创建一个 如果存在这个文件,会接着已有的内容的后面写入 with ope ...
- python读取与写入json+csv变成coco的json文件+安装labelme
一.python读取与输出json 1.python字典和json互转这里用json.dumps,还原则用json.loads,dumps以后就变为字符串了 import json# info = { ...
- 使用Python读取LabVIEW TDMS 格式文件转成Excel格式+多进程版本
使用Python读取LabVIEW TDMS 格式文件转成Excel格式+多进程版本 文章目录 使用Python读取LabVIEW TDMS 格式文件转成Excel格式+多进程版本 前言: 背景 tm ...
- python 读取mat文件,python读取并写入mat文件的方法
先给大家介绍下python读取并写入mat文件的方法 用matlab生成一个示例mat文件: clear;clc matrix1 = magic(5); matrix2 = magic(6); sav ...
- python逐行读取txt写入excel_用python从符合一定格式的txt文档中逐行读取数据并按一定规则写入excel(openpyxl支持Excel 2007 .xlsx格式)...
前几天接到一个任务,从gerrit上通过ssh命令获取一些commit相关的数据到文本文档中,随后将这些数据存入Excel中.数据格式如下图所示 观察上图可知,存在文本文档中的数据符合一定的格式,通过 ...
- python入门文件读取与写入_初学者Python:读取和写入同一文件
每个打开的文件都有一个隐式指针,该指针指示将在何处读取和写入数据.通常,它默认为文件的开头,但是如果您使用a(追加)模式,则默认为文件的结尾.还值得注意的是,w即使您添加+到该模式,该模式也会截断您的 ...
最新文章
- Intellij Idea 生成serialVersionUID的方法
- MOSES | 分子生成模型的基准平台
- 在Stack Overflow如果语言有问题,请写以下英文
- Understand Skills-Based Routing
- UVA 11090 Going in Cycle!! 二分答案 + bellman-ford
- w3c html规范规范文档,前端开发规范
- 有效集法介绍(Active Set Method)
- Pickle Finance:BAC-DAI Pickle Jar将在迁移到BAS v2后更新
- 正则表达式应用笔记----解析网页,获取并显示“未来三天全国天气预报”(java)...
- Electron 使用Widevine CDM插件
- 我是如何黑掉惠普打印机的
- cad剖切线的快捷键_Auto CAD2017剖切符号快捷键是什么呢?
- 配置Json-Server
- ASUS R556L华硕老笔记升级,换固态硬盘,鸟枪换炮记:买固态硬盘的纠结和艰辛的系统迁移(前后花了三天时间)
- P2【商业级MMORPG大型网游】Unity全栈开发 笔记
- 中专学历怎么积分落户北京?
- 【基础】python-docx包之----设置段落样式(缩进/对齐/间距)
- 华为交换机RRPP的基本配置
- java 播放mid_今天编辑了一个播放mid音乐的程序,呵呵,,分享一下我的快乐!...
- mysql查询表中重复记录
热门文章
- 蓝桥杯2019年第十届C/C++省赛C组第一题-求和
- C++中 (n1)和(1n) 分别表示什么意思?
- Android 网络请求(OKHttp框架)
- 7-1 Say Hello to Integers (5 分)
- rk3399_android7.1平台调试sensor流程记录
- TCP三次握手四次挥手介绍
- 【网络基础编程】第三节 C/S
- 5.7.2.4 random() 方法
- 如何在Windows平台下可以方便获取到android的源码?
- shell for while循环