标签:bin 函数 sele 方便 data xlsx tin author word
xlsxwriter,openpyxl,pandas 模块都可以实现往excel中写入数据,但是为了更简单方便的实现我的需求,选择将三种结合使用。
#!/usr/bin/env python3 # -*-coding: utf-8 -*- # @Time:2019/12/26 16:55 # @Author: WSN import pandas as pd import pymysql, openpyxl, os, xlsxwriter # 设定excel文件名称 version = ‘V1.4.6‘ filename = ‘%s版本UAT自动化运维平台工单记录.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‘]) 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(‘%s版本UAT自动化运维平台工单记录.xlsx‘ % (version)) 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(‘数据加载完毕!‘)
python实现自动从mysql数据库取指定数据记录到excel中-新建、追加
标签:bin 函数 sele 方便 data xlsx tin author word
原文地址:https://www.cnblogs.com/wsn-only/p/12132618.html