在工作过程中要定期的更新excel表的信息,每个星期都要去查询strarocks的数据导出结果到excel,俗话说:“不会偷懒的运维不是好运维”,于是写了python小程序解决这个重复的工作,设置定时任务,直接去服务器下载导出的excel表格即可。
代码的逻辑简单介绍:将要执行的SQL以名称进行区分保存并放到目录:SQLfileDir,设置结果存放路径:./…/outputdir/。python先查询数据,然后以SQL文件名前缀为excle名称保存,最后移动到指定目录。
本地调试界面:
# -*- coding: utf-8 -*-
# @Author : zjh
# @Time : 2023-12-27
# @Description: 定时跑数据保存到excel
import os
import shutil
import pandas as pd
import pymysql
import openpyxl
import datetime
class StarRocksExporter(object):
def __init__(self, host, port, database, user, password, query,
srcdir, destdir,filename):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
self.query = query
self.srcdir = srcdir
self.destdir = destdir
self.filename = filename
self.writer = pd.ExcelWriter(filename+str('.xlsx'))
def export_to_excel(self):
df = pd.read_sql(self.query, self.engine)
# print(df)
df.to_excel(self.writer, sheet_name=self.filename, index=False)
self.writer.save()
def move_to_dest(self):
if not os.path.isdir(self.destdir):
self.destdir = os.mkdir(self.destdir)
file_list = os.listdir(self.srcdir)
for file in file_list:
#print(file)
#print(file.split('.')[0])
try:
#print(file.split('.')[1])
fiel_str = file.split('.')[1]
if fiel_str == 'xlsx':
shutil.move(str(self.srcdir) + file, str(self.destdir) + file)
except Exception:
print("没有后缀的文件:",file)
#shutil.move(str(self.srcdir) + file, str(self.destdir) + file)
def execute(self):
with pymysql.connect(host=self.host,port=self.port,database=self.database,user=self.user,password=self.password) as engine:
self.engine = engine
self.query_star_rock(self.query)
self.export_to_excel()
self.move_to_dest()
def query_star_rock(self, query):
cursor = self.engine.cursor()
cursor.execute(query)
results = cursor.fetchall()
return results
def get_user(self, user):
pass
def get_password(self, password):
pass
if __name__ == '__main__':
Destdir = './../outputdir/'
Srcdir = './'
folder_path = './../SQLfileDir/'
file_list = os.listdir(folder_path)
for sqlfile in file_list:
file_path=str(folder_path)+str(sqlfile)
with open(file_path, "r", encoding='utf-8') as f:
sql = f.read()
srfilename = sqlfile.split('.')[0]
exporter = StarRocksExporter('192.168.10.11', 19030, 'manager', 'sys_ro','sdagfsdg!@#saf134',
sql,Srcdir,Destdir,srfilename)
exporter.execute()