Python3读取Excel数据存入MySQL的方法
Python是数据分析的强大利器。
利用Python做数据分析,第一步就是学习如何读取日常工作中产生各种excel报表并存入数据中,方便后续数据处理。
这里向大家分享python3如何使用xlrd读取excel,并使用Python3操作pymysql模块将数据存入Mysql中,有需要的朋友们一起来看看吧。
前言
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。
版本
python>=3.6
mysql>=5.7.19
安装
python、mysql的安装这里就不详细述说了,有需要的朋友自行百度
xlrd:可以使用pip安装也可手动下载源码安装,pip安装:pipinstallxlrd
pymysql:可以使用pip安装也可手动下载源码安装,pip安装:pipinstallxlrd
模块
importxlrd importpymysql fromdatetimeimportdatetime fromxlrdimportxldate_as_tuple
读取excel
data=xlrd.open_workbook("D:/sales_data.xls")//读取D盘中名为sales_data的excel表格
table_one=data.sheet_by_index(0)//根据sheet索引获取sheet的内容
table_two=data.sheet_by_index(1)
创建数据库连接
db=pymysql.connect("localhost","root","gaishi123","sales_data",use_unicode=True,charset="utf8")
gaishi123是mysql的root的密码,sales_data是数据库名
forsiteinsites:
#遍历sheet1
fornrows_oneinrange(1,int(table_one.nrows)):
iftable_one.cell_value(nrows_one,0)==site:
payday=table_one.cell_value(0,8)
date=datetime(*xldate_as_tuple(payday,0))
payday=date.strftime('%Y/%m/%d')#出票日期
sales=float(table_one.cell_value(nrows_one,1))#销量
quantity_ticket=int(table_one.cell_value(nrows_one,2))#票数
rate_electronic=float(table_one.cell_value(nrows_one,3))#电子直销占比
sales_thanlastweek=float(table_one.cell_value(nrows_one,4))#销量同比上周
sales_thanlastyear=float(table_one.cell_value(nrows_one,5))#销量同比去年
break
#遍历sheet2
fornrows_twoinrange(1,int(table_two.nrows)):
iftable_one.cell_value(nrows_two,0)==site:
session=int(table_two.cell_value(nrows_two,1))#访问量
rate_conversion=float(table_two.cell_value(nrows_two,2))#转化率
rate_paysuccess=float(table_two.cell_value(nrows_two,3))#支付成功率
session_thanlastweek=float(table_two.cell_value(nrows_two,4))#访问量同比上周
break
#将数据存入数据库
sql="insertintosales_data(SITE,PAYDAY,SALES,QUANTITY_TICKET,RATE_ELECTRONIC,SALES_THANLASTWEEK,"\
"SALES_THANLASTYEAR,SESSION,SESSION_THANLASTWEEK,RATE_CONVERSION,RATE_PAYSUCCESS)"\
"values('%s','%s',%f,%d,%f,%f,%f,%d,%f,%f,%f)"%\
(site,payday,sales,quantity_ticket,rate_electronic,sales_thanlastweek,sales_thanlastyear,
session,session_thanlastweek,rate_conversion,rate_paysuccess)
try:
#使用cursor()方法创建一个游标对象cursor
cursor=db.cursor()
cursor.execute(sql)
exceptExceptionase:
#发生错误时回滚
db.rollback()
print(str(e))
else:
db.commit()#事务提交
print('事务处理成功')
以上这篇Python3读取Excel数据存入MySQL的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。