使用Python读Excel数据Insert到MySQL

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

#!/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)










本文转自 chengxuyonghu 51CTO博客,原文链接:http://blog.51cto.com/6226001001/1901651,如需转载请自行联系原作者
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
3天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by='A', ascending=False)`。`rank()`函数用于计算排名,如`df['A'].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=['A', 'B'], ascending=[True, False])`和分别对'A'、'B'列排名。
13 2
|
2天前
|
机器学习/深度学习 算法 数据挖掘
PYTHON银行机器学习:回归、随机森林、KNN近邻、决策树、高斯朴素贝叶斯、支持向量机SVM分析营销活动数据|数据分享-2
PYTHON银行机器学习:回归、随机森林、KNN近邻、决策树、高斯朴素贝叶斯、支持向量机SVM分析营销活动数据|数据分享
24 1
|
1天前
|
机器学习/深度学习 算法 Python
数据分享|Python决策树、随机森林、朴素贝叶斯、KNN(K-最近邻居)分类分析银行拉新活动挖掘潜在贷款客户
数据分享|Python决策树、随机森林、朴素贝叶斯、KNN(K-最近邻居)分类分析银行拉新活动挖掘潜在贷款客户
20 4
|
1天前
|
机器学习/深度学习 算法 算法框架/工具
数据分享|PYTHON用KERAS的LSTM神经网络进行时间序列预测天然气价格例子
数据分享|PYTHON用KERAS的LSTM神经网络进行时间序列预测天然气价格例子
21 0
|
1天前
|
机器学习/深度学习 数据挖掘 网络架构
Python对商店数据进行lstm和xgboost销售量时间序列建模预测分析
Python对商店数据进行lstm和xgboost销售量时间序列建模预测分析
12 0
|
2天前
|
数据挖掘 数据处理 索引
如何使用Python的Pandas库进行数据筛选和过滤?
Pandas是Python数据分析的核心库,提供DataFrame数据结构。基本步骤包括导入库、创建DataFrame及进行数据筛选。示例代码展示了如何通过布尔索引、`query()`和`loc[]`方法筛选`Age`大于19的记录。
10 0
|
4天前
|
Python
如何使用Python的Pandas库进行数据缺失值处理?
Pandas在Python中提供多种处理缺失值的方法:1) 使用`isnull()`检查;2) `dropna()`删除含缺失值的行或列;3) `fillna()`用常数、前后值填充;4) `interpolate()`进行插值填充。根据需求选择合适的方法处理数据缺失。
36 9
|
分布式计算 关系型数据库 MySQL
E-Mapreduce如何处理RDS的数据
目前网站的一些业务数据存在了数据库中,这些数据往往需要做进一步的分析,如:需要跟一些日志数据关联分析,或者需要进行一些如机器学习的分析。在阿里云上,目前E-Mapreduce可以满足这类进一步分析的需求。
4935 0
|
16天前
|
关系型数据库 MySQL 数据库
mysql卸载、下载、安装(window版本)
mysql卸载、下载、安装(window版本)
|
5天前
|
关系型数据库 MySQL 数据库
《MySQL 简易速速上手小册》第1章:MySQL 基础和安装(2024 最新版)
《MySQL 简易速速上手小册》第1章:MySQL 基础和安装(2024 最新版)
28 4