python连接数据库,处理数据结果后生成excel文件
# _*_coding:utf-8 _*_
import time
import xlwt
import os
import pymysql
import sys
import datetime
from datetime import datetime, timedelta
class writefile:
? ? file = r"D:\Users\xx\Desktop"
? ? #查詢數據庫結果
? ? def datacommon(self,mounth,day,n,abj):
? ? ? ? res = []
? ? ? ? self.date1 = self.dates(mounth,day,n,abj)
? ? ? ? for date in self.date1:
? ? ? ? ? ? starttime = date + ' 00:00:00'
? ? ? ? ? ? endtime = date + ' 23:59:59'
? ? ? ? ? ? #連接數據庫
? ? ? ? ? ? db = pymysql.connect(host="12.12.12.12", user="root", password="sqldb",port=3306, db="test")
? ? ? ? ? ? # 使用cursor()方法獲取操作游標
? ? ? ? ? ? cursor = db.cursor()
? ? ? ? ? ? cursor.execute(f"SELECT project_name FROM `data`.`table` WHERE project_name like \"%test%\" AND create_time between '{starttime}' and '{endtime}'")
? ? ? ? ? ? project_name = sorted(set(cursor.fetchall()))
? ? ? ? ? ? for name in project_name:
? ? ? ? ? ? #計算主線數據
? ? ? ? ? ? ? ? cursor.execute(f"SELECT count(*) FROM `data`.`table` where branch_name like lower(trim(\"%-{name[0]}\")) AND status=0 AND create_time between '{starttime}' and '{endtime}'")
? ? ? ? ? ? ? ? succ_NUM = cursor.fetchall()[0][0]
? ? ? ? ? ? ? ? cursor.execute(f"SELECT count(*) FROM `data`.`table` where branch_name like lower(trim(\"%-{name[0]}\")) AND status=2 AND create_time between '{starttime}' and '{endtime}'")
? ? ? ? ? ? ? ? fail_NUM = cursor.fetchall()[0][0]
? ? ? ? ? ? ? ? if fail_NUM !=0 and succ_NUM !=0:
? ? ? ? ? ? ? ? ? ? fail_RATE = "%.2f%%" % (fail_NUM / (succ_NUM + fail_NUM) * 100)
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? fail_RATE = 0
? ? ? ? ? ? ? ? ?#計算分支數據
? ? ? ? ? ? ? ? cursor.execute(f"SELECT count(*) FROM `data`.`table` where branch_name like lower(trim(\"%-{name[0]}-%\")) AND status=0 AND create_time between '{starttime}' and '{endtime}'")
? ? ? ? ? ? ? ? succ_num = cursor.fetchall()[0][0]
? ? ? ? ? ? ? ? cursor.execute(f"SELECT count(*) FROM `data`.`table` where branch_name like lower(trim(\"%-{name[0]}-%\")) AND status=2 AND create_time between '{starttime}' and '{endtime}'")
? ? ? ? ? ? ? ? fail_num = cursor.fetchall()[0][0]
? ? ? ? ? ? ? ? if fail_num !=0 and succ_num !=0:
? ? ? ? ? ? ? ? ? ? fail_rate = "%.2f%%" % (fail_num / (succ_num + fail_num) * 100)
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? fail_rate = 0
? ? ? ? ? ? ? ? res1 = [date,name[0], succ_num, fail_num, fail_rate, succ_NUM, fail_NUM, fail_RATE]
? ? ? ? ? ? ? ? res.append(res1)
? ? ? ? return res
? ? ? ? # 關閉數據庫連接
? ? ? ? db.close()
? ? # 判斷文件是否已存在
? ? def if_file_exist(self):
? ? ? ? if os.path.exists(self.file + "\數據展示.xls"):
? ? ? ? ? ? os.remove(self.file + "\數據展示.xls")
? ? # 生成excel
? ? def write_excel(self, res):
? ? ? ? book = xlwt.Workbook() ?# 新建一個excel
? ? ? ? sheet = book.add_sheet('導出數據') ?# 創建sheet
? ? ? ? title = ['統計區間', '版本','個人信息成功', '個人信息失敗', '個人信息有效攔截率', '主線信息通過','主線信息失敗','主線信息有效攔截率', '問題分析'] ?# 寫表頭
? ? ? ? # 循環將title寫入excel表頭
? ? ? ? i = 0
? ? ? ? for header in title:
? ? ? ? ? ? sheet.write(0, i, header)
? ? ? ? ? ? i += 1
? ? ? ? # 將數據寫入Excel
? ? ? ? for row in range(1, len(res) + 1):
? ? ? ? ? ? for col in range(0, len(res[row - 1])):
? ? ? ? ? ? ? ? sheet.write(row, col, res[row - 1][col])
? ? ? ? ? ? ? ? col += 1
? ? ? ? ? ? row += 1
? ? ? ? book.save(self.file + "\數據展示.xls")
? ? ? ? print("導出成功")
? ? def dates(self,mounth,day,n=7,abj=0):
? ? ? ? for i in range(1,n+1):
? ? ? ? ? ? if abj != 0:
? ? ? ? ? ? ? ? the_date = datetime.datetime(2021, mounth, day) ?# 指定當前日期 2018-11-10
? ? ? ? ? ? ? ? the_date = the_date - datetime.timedelta(days=i)
? ? ? ? ? ? ? ? date = the_date.strftime('%Y-%m-%d') ?# 將日期轉換為指定的顯示格式
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? date = time.strftime('%Y-%m-%d', time.localtime(time.time() - 86400 * i))
? ? ? ? ? ? yield date
? ? def writefile(self):
? ? ? ? n=7 ? ? ? ? ? #統計天數,默認為7天
? ? ? ? mounth = 12 ? #統計日期
? ? ? ? day = 12 ? ? ?#統計日期
? ? ? ? abj= 0 ? ? ? ?#若值為0,則使用當前日期統計;若值為非0,則使用變量日期統計;默認為當前日期為準
? ? ? ? self.if_file_exist()
? ? ? ? res = self.datacommon(mounth,day,n,abj)
? ? ? ? self.write_excel(res)
a=writefile()
a.writefile()
總結
以上是生活随笔為你收集整理的python连接数据库,处理数据结果后生成excel文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有关运维面试重点
- 下一篇: Java开发者的Python快速进修指南