My python is not very good, so I copied it after imitating the big guys, using python3, and then the rest, the environment and the like are taken care of by myself, I will directly upload the code below, mainly for me I used it for my own review. There is definitely no problem with the execution. The rest of the details are reported wrong, because I need to change the date of the day to generate the excel file. I used the shell to change the name before, and then I thought about it. , Just try to see if python can be changed directly, it is best if it can be changed, and in the end, it can be changed, haha
#!/usr/bin/env python3 # coding: utf-8 import them import xlwt import pymysql import datetime #####Special note: The def function in the class must be consistent with the above position, do not use tabs in indentation, must use spaces, and must be consistent with the above content format, otherwise You have found the wrong one! ! ! ! ! ! # Online customer service data statistics class MysqlToExcel(object): def __init__(self): self.host = '127.0.0.1' self.user = 'root' self.passwd = 'gxbw2020' self.db_name = 'contact center_zhengshi' self.port = 3306 self.time_now = datetime.datetime.now().strftime("%Y-%m-%d") self.file_name = self.time_now +'Online customer service data statistics.xls' ###########Query sheet1################################# ######### def get_query_results1(self): sql1 = "select l.record_date 记录日期,u.uname 用户名,o.name 部门名,op.name 区县,opp.name 市级 from uk_agentstatus_log l left join uk_user u on l.user_id = u.id left join uk_organ o on o.id = u.ORGAN left join uk_organ op on o.parent = op.id left join uk_organ opp on op.parent = opp.id where l.record_date = (select date_format(now(),'%Y-%m-%d')) order by l.record_date,opp.name,op.name,o.name" conn = pymysql.connect( host=self.host, user=self.user, passwd=self.passwd, port=self.port, database=self.db_name, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) cur = conn.cursor() # create a cursor cur.execute(sql1) # execute sql command result1 = cur.fetchall() # Get the result of execution # print(result) cur.close() conn.close() # Close mysql connection return result1 ###########Query sheet2################################# def get_query_results2(self): sql2 = "select uo3.name as city level, uo2.name as county level, count(s.aiservice) manual access, 0 as'robot access' from uk_agentservice s left join uk_user u on s.agentno=u .id left join uk_organ uo1 on uo1.id=u.organ left join uk_organ uo2 on uo2.id=uo1.PARENT left join uk_organ uo3 on uo3.id=uo2.parent where s.createtime BETWEEN curdate() AND date_sub(curdate (),interval-1 day) and s.aiservice='0' and s.agentno != '' and u.id is not null group by uo2.name union all select'robot' as municipal,'robot' as County, 0 as'Manual access', count(s.aiservice) Robot access from uk_agentservice s where s.createtime BETWEEN curdate() AND date_sub(curdate(),interval-1 day) and s.aiservice= '1'" conn = pymysql.connect( host=self.host, user=self.user, passwd=self.passwd, port=self.port, database=self.db_name, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) cur = conn.cursor() # create a cursor cur.execute(sql2) # execute sql command result2 = cur.fetchall() # Get the result of execution # print(result) cur.close() conn.close() # Close mysql connection return result2 ###############Query sheet3############################## ################### def get_query_results3(self): sql3 = "select u.uname as'username', count(s.result ='very satisfied' or null) as'very satisfied', count(s.result ='satisfied' or null) as'satisfied', count (s.result ='not satisfied' or null) as'not satisfied' from uk_agentstatis s left join uk_user u on u.id = s.agentno where s.time BETWEEN curdate() AND date_sub(curdate(),interval-1 day) group by u.uname;" conn = pymysql.connect( host=self.host, user=self.user, passwd=self.passwd, port=self.port, database=self.db_name, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) cur = conn.cursor() # create a cursor cur.execute(sql3) # execute sql command result3 = cur.fetchall() # Get the result of execution cur.close() conn.close() # Close mysql connection return result3 ################Query sheet4############################ ###################### def get_query_results4(self): sql4 = "select distinct uo2.name as '未在线的县区' from uk_user u left join uk_organ uo1 on uo1.id=u.organ left join uk_organ uo2 on uo2.id=uo1.parent where uo2.name not in( select DISTINCT uo2.name from (select organ from uk_user where id in (select user_id from uk_agentstatus_log where record_date = (select date_format(now(),'%Y-%m-%d')))) t left join uk_organ uo1 on t.organ=uo1.id left join uk_organ uo2 on uo1.parent=uo2.id where uo1.name like '%局端%' and uo1.name not like '%二线%') and uo1.name like '%局端%' and uo2.name != '广西壮族自治区' and uo1.name not like '%二线%';" conn = pymysql.connect( host=self.host, user=self.user, passwd=self.passwd, port=self.port, database=self.db_name, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) cur = conn.cursor() # create a cursor cur.execute(sql4) # execute sql command result4 = cur.fetchall() # Get the result of execution cur.close() conn.close() # Close mysql connection return result4 ################# Query sheet5################################################################################################################################################################################################################################################################# ######################## def get_query_results5(self): sql5 = "select count(uac.nsrsbh) as '转QQ数量', usa.swjgdm as '税务机关代码', usa.swjgmc as '税务机关名称' from uk_agent_connect uac left join uk_sw_area usa on left(uac.swjgdm,7) = left(usa.swjgdm,7) where uac.requestTime like (select concat(curdate(),'%')) and uac.serviceType = 'qq' and uac.nsrsbh is not null and uac.nsrsbh != 'undefined' and uac.swjgdm not like '%,%' and usa.swjgdm is not null and TIME(uac.requestTime) between '08:30:00' and '17:00:00' and TIME(uac.requestTime) not between '12:00:00' and '15:00:00' group by usa.swjgdm order by count(uac.nsrsbh) desc;" conn = pymysql.connect( host=self.host, user=self.user, passwd=self.passwd, port=self.port, database=self.db_name, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) cur = conn.cursor() # create a cursor cur.execute(sql5) # execute sql command result5 = cur.fetchall() # Get the return result of execution cur.close() conn.close() # Close mysql connection return result5 #####################Generating Form############################################################################################################################################################################################################################################################################ ################## def generate_table(self): """ Generate excel sheet :return: """ # Delete existing files if os.path.exists(self.file_name): os.remove(self.file_name) result1 = self.get_query_results1() result2 = self.get_query_results2() result3 = self.get_query_results3() result4 = self.get_query_results4() result5 = self.get_query_results5() ## print(result) #if not result1: # print("The query result is empty") # return False # Create excel object f = xlwt.Workbook() sheet1 = f.add_sheet('Sheet1', cell_overwrite_ok=True) sheet2 = f.add_sheet('Sheet2', cell_overwrite_ok=True) sheet3 = f.add_sheet('Sheet3', cell_overwrite_ok=True) sheet4 = f.add_sheet('Sheet4', cell_overwrite_ok=True) sheet5 = f.add_sheet('Sheet5', cell_overwrite_ok=True) # Column field column_names1 = ['record date','user name','department name','district/county','city level'] column_names2 = ['City-level','County-level','Manual access','Robot access'] column_names3 = ['username','very satisfied','satisfied','not satisfied'] column_names4 = ['Counties not online'] column_names5 = ['number of transferred QQ','tax authority code','tax authority name'] # Write the first row, which is the row where the column is located for e in range(0, len(column_names1)): sheet1.write(0, e, column_names1[e]) for i in range(0, len(column_names2)): sheet2.write(0, i, column_names2[i]) for j in range(0, len(column_names3)): sheet3.write(0, j, column_names3[j]) for g in range(0, len(column_names4)): sheet4.write(0, g, column_names4[g]) for k in range(0, len(column_names5)): sheet5.write(0, k, column_names5[k]) # Modify the timestamp format of excel generated by python dateFormat = xlwt.XFStyle() dateFormat.num_format_str = 'yyyy/mm/dd' # Write multiple lines num1 = 0 # counter for e in result1: sheet1.write(num1 + 1, 0, e['record date'],dateFormat) #Convert the format of the record date and no longer display 5 digits sheet1.write(num1 + 1, 1, e['user name']) sheet1.write(num1 + 1, 2, e['department name']) sheet1.write(num1 + 1, 3, e['districts']) sheet1.write(num1 + 1, 4, e['municipal']) num1 += 1 # Increment 1 num2 = 0 # counter for i in result2: sheet2.write(num2 + 1, 0, i['municipal level']) sheet2.write(num2 + 1, 1, i['county level']) sheet2.write(num2 + 1, 2, i['Manual access']) sheet2.write(num2 + 1, 3, i['Robot access amount']) num2 += 1 # Increment 1 num3 = 0 # counter for j in result3: sheet3.write(num3 + 1, 0, j['Username']) sheet3.write(num3 + 1, 1, j['Very satisfied']) sheet3.write(num3 + 1, 2, j['satisfied']) sheet3.write(num3 + 1, 3, j['not satisfied']) num3 + = 1 num4 = 0 # counter for g in result4: sheet4.write(num4 + 1, 0, g['Counties not online']) num4 + 1 = num5 = 0 # counter for k in result5: sheet5.write(num5 + 1, 0, k['to QQ quantity']) sheet5.write(num5 + 1, 1, k['tax authority code']) sheet5.write(num5 + 1, 2, k['Name of tax authority']) num5 += 1 ################################################################# # save document f.save(self.file_name) # Determine whether the file exists if not os.path.exists(self.file_name): print("Failed to generate excel") return False print("Excel generated successfully") return True if __name__ == '__main__': MysqlToExcel().generate_table()