# encoding: utf-8
import time
import pandas as pd
import pymysql
def getrel(sql):
'''
连接mysql数据库,根据条件查询出来我们所需要数据
:return: 根据条件从sql查询出来的数据
'''
conn = pymysql.connect(host='localhost', user='root', password='',
db='db_test', charset='utf8mb4')
cur = conn.cursor()
cur.execute(sql) # 输入要查询的SQL
rel = cur.fetchall()
cur.close()
conn.close()
return rel
def getxlsx(rel):
'''
把从数据库中查询出来的数据写入excel文件
:param rel:
:return:
'''
file_name = time.strftime('%Y-%m-%d') + '.xlsx'
dret = pd.DataFrame.from_records(list(rel)) # mysql查询的结果为元组,需要转换为列表
dret.to_excel(file_name, index=False, header=("平台货号", "商品名称", "售价")) # header 指定列名,index 默认为True,写行名
if __name__ == '__main__':
sql = 'select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;'
rel = getrel(sql)
getxlsx(rel)
import pymysql
import xlwt
def get_sel_excel(sql):
'''
连接mysql并把查询出来的数据写入excel表格
:param sql:
:return:
'''
conn = pymysql.connect(
host="localhost",
port=3306,
user="root",
passwd="",
db="db_test",
charset="utf8mb4"
)
# 建立游标
cursor = conn.cursor()
print("开始查询表!")
# 执行sql语句
cursor.execute(sql)
# 获取查询到结果
res = cursor.fetchall()
print(res)
w\_excel(res)
def w_excel(res):
'''
把数据写入excel表格中
:param res:
:return:
'''
book = xlwt.Workbook() # 新建一个excel
sheet = book.add_sheet('vehicle_land') # 新建一个sheet页
title = ['平台货号', '商品名称', '售价']
# 写表头
i = 0
for header in title:
sheet.write(0, i, header)
i += 1
# 写入数据
for row in range(1, len(res)):
for col in range(0, len(res\[row\])):
sheet.write(row, col, res\[row\]\[col\])
row += 1
col += 1
book.save('vehicle\_land.xls')
print("导出成功!")
if __name__ == "__main__":
sql = 'select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;'
get_sel_excel(sql)
import pandas as pd
from sqlalchemy import create_engine
sql = """select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;"""
df = pd.read_sql_query(sql,con=engine)
print(df)
writer = pd.ExcelWriter('mydf.xlsx')
df.to_excel(writer,sheet_name='test1',index=False)
writer.save()
# coding=utf-8
import pandas as pd
from pandas import DataFrame
from sqlalchemy import create_engine
import time
start = time.time()
engine = create_engine('mysql+pymysql://root:123@192.168.148.61:3306/ppx_mall_dev_db')
sql = '''select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;'''
df = pd.read_sql_query(sql, engine)
print("从mysql中读取数据成功!开始将数据导入到excel表格中…")
test_data = DataFrame.from_records(df)
test_data.to_excel("E:\\testdata.xlsx", index=False)
print("导出成功!")
end = time.time()
print('Running time: {} Seconds'.format(end - start))
如需修改表格样式,可参数:https://www.cnblogs.com/phoebechiang/p/10512337.html
手机扫一扫
移动阅读更方便
你可能感兴趣的文章