下载包
pip install pymysql
pip install xlwt
源代码
MySQL数据转Excel
import pymysql
import xlwt
# 获取数据库连接
conn=pymysql.connect(
host='localhost',
user='root', # 自己的用户名
password='010401', # 自己的密码
db='shuxuejianmo', # 数据库名
charset='utf8',
)
print("数据库连接成功")
#获取游标
curs=conn.cursor()
#SQL语句
sql = 'SELECT left(dt,4) dt, avg(AverageTemperature) avgg from c where Country = \'China\' and AverageTemperature is not null group by left(dt,4) ORDER BY left(dt,4)'
# 执行SQL语句
curs.execute(sql)
#获取所有数据
rows=curs.fetchall()
print(rows)
#初始化excel文件
w=xlwt.Workbook(encoding='utf-8')
style=xlwt.XFStyle()#初始化样式
font=xlwt.Font()#创建字体样式
font.name="微软雅黑"
style.font=font#把字体添加到样式中
ws=w.add_sheet("用户信息",cell_overwrite_ok=True)
#把数据写入excel
'''创建excel的列名,读个列名中间用,隔开'''
title="日期,平均温度)"
title=title.split(",")
'''#使用循环写入列名'''
for i in range(len(title)):
ws.write(0,i,title[i],style)
#开始写入数据
for i in range(len(rows)):
row=rows[i]
for j in range(len(row)):
if row[j]:
item=row[j]
ws.write(i+1,j,item,style)
#四、数据保存到本地
path='数据.xls'
w.save(path)
conn.close()
print("保存成功!")
Excel数据转MySQL
# -*- coding: utf-8 -*-
# coding: utf-8
# 引入Excel库的xlrd
import datetime
import os
import xlrd
import pymysql
from xlrd import xldate_as_tuple
# 创建一个空列表,存储Excel的数据
tables = []
# 将excel表格内容导入到tables列表中
def import_excel(excel):
for rown in range(excel.nrows):
array = {'jingdu': '', 'weidu': '', 'nianfen': '', 'pingjunqiwen': '', }
array['jingdu'] = table.cell_value(rown, 3)
array['weidu'] = table.cell_value(rown, 4)
array['nianfen'] = table.cell_value(rown, 5)
array['pingjunqiwen'] = table.cell_value(rown, 6)
if array['jingdu'] == '经度':
continue
tables.append(array)
# 连接数据库
conn = pymysql.connect(
host="127.0.0.1",
user="root",
password="010401",
database="shuxuejianmo",
charset="utf8"
)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
# 得到一个可以执行SQL语句并且将结果作为字典返回的游标
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
if __name__ == '__main__':
filenames = os.listdir(r'城市气温数据/城市气温数据')
for file in filenames:
# 结果数据集
data = []
# 导入需要读取Excel表格的路径
excelData = xlrd.open_workbook(r'城市气温数据/城市气温数据/'+file)
table = excelData.sheets()[0]
# 将excel表格的内容导入到列表中
import_excel(table)
# 验证Excel文件存储到列表中的数据
sql = 'insert into mathdata values (%s,%s,%s,%s)'
res = []
for i in tables:
data.append((i['jingdu'], i['weidu'], i['nianfen'], i['pingjunqiwen']))
# 执行批量插入数据
cursor.executemany(sql, data)
tables = []
# 提交事务
conn.commit()
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()