在日常数据处理时,经常需要把数据导入到同一个excel中的多个sheet中,如果单纯使用手工操作是不是很麻烦,下面呢,我们就介绍一种简单的方法,利用python一次性将数据库的数据导入到excel的多个sheet中。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sshtunnel
import pymysql
import xlsxwriter
import logging
# 输出到控制台
logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',level=logging.INFO)
def get_sshData2(sql):
with sshtunnel.SSHTunnelForwarder(
ssh_address_or_host='XXX.XX.XX.XXX',
ssh_port=XXXXX,
ssh_username='XXXX',
ssh_password='XXXX',
remote_bind_address=('XXXX.mysql.rds.aliyuncs.com', 3306)
) as tunnel:
try:
conn = pymysql.connect(host='XXX.X.X.X', user='XXX', passwd='XXXX', db='XXXX',
port=tunnel.local_bind_port, charset='utf8');
cursor = conn.cursor()
cursor.execute(sql)
except ConnectionError as e:
logging.error('数据库执行出错:%s', e)
# 使用 fetchone() 方法获取单条数据.
results = cursor.fetchall()
logging.info('sql执行结果:%s', results)
# 关闭数据库连接
conn.close()
# 返给结果给函数调用者。
return results
def writer_data_to_excel():
sql = '''SELECT dd '日期',
CONCAT(ROUND(SUM(mount)/10000,2),'万')'mount1',
CONCAT(ROUND(SUM(mount1)/10000,2),'万')'mount2',
CONCAT(ROUND(SUM(mount3)/10000,2),'万')'mount3',
CONCAT(ROUND(SUM(mount2)/10000,2),'万')'mount4',
CONCAT(ROUND(SUM(mount1)*100/SUM(mount),2),'%')'mount5'
FROM (
SELECT a.dd dd,
a.user_id user_id,
a.mount mount ,
IF(a.mount>IFNULL(b.mount,0),IFNULL(b.mount,0),a.mount) mount1 ,
IF(a.mount-IFNULL(c.tx,0)-IFNULL(b.mount,0)>0, a.mount-IFNULL(c.tx,0)-IFNULL(b.mount,0),0)mount2,
IF(a.mount>IFNULL(c.tx,0),IFNULL(c.tx,0),a.mount) mount3
FROM (
#当日实际回款金额
SELECT FROM_UNIXTIME(recover_yestime,'%Y-%m-%d')dd,user_Id,SUM(recover_account_yes/100)mount FROM depository_borrow_recover
WHERE STATUS=1
AND FROM_UNIXTIME(recover_yestime,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d')
AND user_id NOT IN (XX,XXX,XXXXX)
AND user_id IN (SELECT user_id FROM deayou_users
WHERE internal_status=0) GROUP BY user_id )a
LEFT JOIN (
#当日投资金额
SELECT user_id ,SUM(dd.mount) mount
FROM (
SELECT user_id,account/100 mount FROM d_table1
WHERE borrow_nid>0
AND tender_type<>'zq'
AND join_id IS NULL
AND FROM_UNIXTIME(ADDTIME,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d')
UNION ALL
SELECT user_id,join_money/100 mount FROM d_table2
WHERE DATE_FORMAT(add_time,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d'))dd
GROUP BY user_id)b ON a.user_id=b.user_id
LEFT JOIN (
#当日提现金额
SELECT user_id,
SUM(`total`) /100 tx
FROM `d_table3`
WHERE `status`= 1
AND user_id NOT IN (XX,XXX,XXXXXX)
AND FROM_UNIXTIME(ADDTIME, '%Y-%m-%d')=date_format(now(),'%Y-%m-%d')
GROUP BY user_id) c ON a.user_id=c.user_id)nn'''
results = get_sshData2(sql)
# 新建文档
workbook = xlsxwriter.Workbook('18.xlsx')
# 创建sheet页
worksheet1 = workbook.add_worksheet('sheet1')
worksheet2=workbook.add_worksheet('sheet2')
# border:边框,align:对齐方式,bg_color:背景颜色,font_size:字体大小,bold:字体加粗
bold_format = workbook.add_format({'bold': True}) # 设置单元格格式
workformat=workbook.add_format()
workformat.set_align('center')
# 设置列宽
worksheet1.set_column("A:L", 16,workformat) # 设定A列列宽为40
# 添加标题
title = ['日期', '实际收到金额', '当日支出金额', '当日成本金额', '当日站岗资金', '占比']
worksheet1.write('A1', "当日占比计算方法",bold_format)
worksheet1.write_row('A2', title)
# 遍历结果集中的每个元素,将数据写入新建的sheet页中
for i in range(len(results)):
for j in range(len(results[i])):
worksheet1.write(i + 2, j, results[i][j])
sql4 = ''' SELECT a.mount '未收资金',
b.mount '已收资金'
FROM (
(
SELECT IFNULL(SUM(recover_account/100),0)mount FROM d_bow_rever
WHERE STATUS=0
AND user_id NOT IN (XX,XXX,XXXX)
AND user_id NOT IN (SELECT user_id FROM t_inside_users)
AND FROM_UNIXTIME(recover_time,'%Y-%m-%d')=DATE_FORMAT(NOW(),'%Y-%m-%d'))a,
(
SELECT IFNULL(SUM(recover_account_yes/100),0)mount FROM d_bow_rever
WHERE STATUS=1
AND user_id NOT IN (XX,XXX,XXXX)
AND user_id NOT IN (SELECT user_id FROM `t_inside_users` ORDER BY `user_id` DESC)
AND FROM_UNIXTIME(recover_yestime,'%Y-%m-%d')=DATE_FORMAT(NOW(),'%Y-%m-%d'))b)''';
results4 = get_sshData2(sql4)
# 添加标题
title4 = ['未收金额', '已收金额']
worksheet2.write('A1', "资金变化:", bold_format)
worksheet2.write_row('A2', title4)
# 遍历结果集中的每个元素,将数据写入新建的sheet页中
for i in range(len(results4)):
for j in range(len(results4[i])):
worksheet2.write(i + 2, j, results4[i][j])
workbook.close()
# 调用上面的方法写入
writer_data_to_excel()
运行之后,记得到我们想要的结果(如下图):
以上这篇用Python将mysql数据库导入excel多个sheet中就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多关注哦。
欢迎大家关注公众号【夏目笔记】,一起探讨python在数据分析中的应用。