由于每天到公司都需要先执行一遍检测操作,观察数据是否导入完整,今天想到能否自动连接Mysql执行SQL并导出数据,每天到公司直接查看excel文件即可
时间紧,代码以及excel格式还没有调,初次试验,边摸索边学习吧。sql代码那句总想能不能用个变量代替,显得太冗长了
#coding:utf-8 import MySQLdb import xlsxwriter import datetime import os today = datetime.date.today() oldfile=‘demo‘+str(today.day-2)+‘.xlsx‘ newfile=‘demo‘+str(today.day-1)+‘.xlsx‘ if os.path.isfile(oldfile) : os.remove(oldfile) else: pass def getdata(): conn = MySQLdb.connect(host=‘服务器IP地址‘, user=‘root‘, passwd=‘服务器密码‘, db=‘local_db‘, port=3306, charset=‘utf8‘) cursor = conn.cursor() test_sql = ‘‘‘ SELECT DATE(订单日期) AS 订单日期,ROUND(SUM(金额)) AS 总计 ,ROUND(SUM(IF(城市="北京",金额,NULL))) AS 北京,ROUND(SUM(IF(城市="成都",金额,NULL))) AS 成都 ,ROUND(SUM(IF(城市="杭州",金额,NULL))) AS 杭州,ROUND(SUM(IF(城市="济南",金额,NULL))) AS 济南,ROUND(SUM(IF(城市="长春",金额,NULL))) AS 长春 ,ROUND(SUM(IF(城市="青岛",金额,NULL))) AS 青岛,ROUND(SUM(IF(城市="南京",金额,NULL))) AS 南京,ROUND(SUM(IF(城市="郑州",金额,NULL))) AS 郑州 ,ROUND(SUM(IF(城市="西安",金额,NULL))) AS 西安 FROM a003_order WHERE 金额>0 AND DATE(订单日期)>=DATE_ADD(CURRENT_DATE,INTERVAL -15 DAY) AND DATE(订单日期)<CURRENT_DATE GROUP BY DATE(订单日期) ‘‘‘ count=cursor.execute(test_sql) conn.commit() data=cursor.fetchall() cursor.close() conn.close() return data def write_excel(): data=getdata() workbook = xlsxwriter.Workbook(newfile) worksheet = workbook.add_worksheet(‘data‘) dic1 = {0: "订单日期", 1: "总计", 2: "北京", 3: "成都", 4: "杭州", 5: "济南", 6: "长春", 7: "青岛", 8: "南京", 9: "郑州", 10: "西安"} for i in range(0, 11): title = dic1[i].decode(‘utf-8‘) worksheet.write(0, i, title) for x in range(0, 15): for y in range(0, 11): db = str(data[x][y]).decode(‘utf-8‘) worksheet.write(x + 1, y, db) workbook.close() print write_excel()
执行导出到excel是下图 数据已处理 明天执行时候会先删除今天执行生成的文件
时间: 2024-10-03 04:36:42