‘‘‘ 需求:写一个函数,随便输入一个表名,把这个表里面所有的数据,导出到excel里面 思路: 1、‘select * from %s‘ ,查出这个表所有的数据 2、再把所有的数据写到excel xlwt ‘‘‘ import pymysql,hashlib,xlwt def op_mysql(sql:str): mysql_info = { ‘host‘: ‘XXX.XXX.XXX.XXX‘, ‘port‘: XXXX, ‘password‘: ‘XXXX‘, ‘user‘: ‘XXXX‘, ‘db‘: ‘XXXX‘, ‘charset‘: ‘utf8‘, ‘autocommit‘: True } result = ‘执行完成‘ conn = pymysql.connect(**mysql_info) # cur = conn.cursor(pymysql.cursors.DictCursor) #建立游标 cur = conn.cursor() #建立游标 cur.execute(sql) field = [ t[0] for t in cur.description ] #获取表里面的所有字段名 if sql.strip().lower().startswith(‘select‘): # result = cur.fetchone() result = cur.fetchall() cur.close() conn.close() print(‘所有的字段‘,field) print(‘所有的数据‘,result) result = list(result) #因为返回的是元组,不能修改,所以转成list result.insert(0,field) #加入到最前面 return result def export_excel(table_name): sql =‘select * from %s;‘%table_name result = op_mysql(sql) book = xlwt.Workbook() sheet = book.add_sheet(‘sheet‘) for row, line in enumerate(result): for col, t in enumerate(line): sheet.write(row, col, t) book.save(‘%s.xls‘%table_name) export_excel(‘CJ_test‘) export_excel(‘app_myuser‘) import xlwt book = xlwt.Workbook() sheet = book.add_sheet(‘sheet‘)l = [ [1,‘dsk‘,‘xxdfsdfsd‘,0], [2,‘ldd‘,‘xxdfsdfsd‘,0], [3,‘lsdd‘,‘xxdfsdfsd‘,0], [4,‘lsd1‘,‘xxdfsdfsd‘,0], ] # 方法一: # row = 0#行号 # for line in l: #外面这个循环,每循环一次,就写excel里面一行 # # col = 0#列号 [1,‘dsk‘,‘xxdfsdfsd‘,0] # col = 0 # for t in line:#里面这个循环是控制列的,每循环一次就写一列 # sheet.write(row,col,t) # col+=1 # row+=1 # # 方法二: for row,line in enumerate(l): for col,t in enumerate(line): sheet.write(row,col,t) book.save(‘user.xls‘)
原文地址:https://www.cnblogs.com/huoxn/p/10919413.html
时间: 2024-10-20 23:50:49