前提:工作要求将DB运维平台每个版本上生产的工单详情记录到excel中,平台导出功能仅有SQL类别,每次记录或者连接平台数据库后台查询导出太过麻烦,故写了这个脚本减少工作量。
xlsxwriter,openpyxl,pandas 模块都可以实现往excel中写入数据,可选择将三种结合使用。
#!/usr/bin/env python
# -*-coding: utf-8 -*-
# @Time:2019/12/26 16:55
# @Author: WSN
# import sys
# sys.path.append('C:\\Users\\wsn\\PycharmProjects\\mypy\\venv\\Lib\\site-packages\\')
import pandas as pd
import pymysql, openpyxl, os, xlsxwriter
# 设定excel文件名称
version = 'V1.4.6'
filename = '%s版本DB运维一体化平台工单记录.xlsx' % (version)
os.chdir('C:\\a_myfile')
# 连接mysql数据库
settings = {"host": "192.168.7.180",
"database": "autosql_prod2",
"user": "root",
"password": "123456",
"port": 3306,
"charset": "utf8"}
db = pymysql.connect(host=settings['host'], database=settings['database'], user=settings['user'],
password=settings['password'], port=settings['port'], charset=settings['charset'])
# 追加到已有excel文件时,更改此处SQL条件
sql = 'SELECT b.WFI_WORKNO 工单号,b.WFI_VERSIONNO 版本号,b.WFI_APPCODE 应用,DATE_FORMAT(DATE_SUB(a.WORKINFO_UPDATETIME, INTERVAL 0 MONTH),' \
'\'%Y-%m-%d\') 日期,b.WFI_EXECUTEENV 执行环境,b.WFI_FILENAME 脚本名称 FROM t_as_workfileinfo b,t_as_workinfo a ' \
'WHERE b.`WFI_WORKNO` = a.WORKINFO_WORKNO AND a.WORKINFO_WORKSTATE = \'07\'' \
'and b.WFI_VERSIONNO=\'V1.4.7\' order by b.WFI_WORKNO '
# 将SQL返回结果存储为dataFrame格式
data = pd.read_sql(sql, db)
# rownu为查询结果的条数
rownu = data.index.stop
# 追加数据到已有excel文件中
def insertexcel():
workbook = openpyxl.load_workbook(filename)
sheet = workbook['Sheet1']
for i in range(0, rownu):
sheet.append(list(data.values[i]))
workbook.save(filename)
workbook.close()
# 新建excel文件中,并设置列表头格式
def newexcel():
workbook = xlsxwriter.Workbook(filename)
sheet = workbook.add_worksheet()
sheet.set_column('A:A', 30)
sheet.set_column('B:E', 11)
sheet.set_column('F:F', 75)
heading = list(data)
headbold = workbook.add_format({'bold': True,
'align': 'center',
'border': 1,
'bg_color': '#D3D3D3'})
sheet.write_row('A1', heading, headbold)
for i in range(0, rownu):
sheet.write_row('A%s' % (i + 2), data.values[i])
workbook.close()
# 判断文件是否存在并运行相应函数
if os.path.exists(filename):
print('----文件已存在,将追加数据到%s----' % filename)
insertexcel()
else:
print('----文件不存在,将新建文件%s----' % filename)
newexcel()
print('数据加载完毕!')