输入任意表名,导出表数据到excel

需求:输入任意表名,导出表数据到excel

  分析:

    1、连接数据库

      1、db_info连接数据库信息

      2、连接数据库:pymysql.connect(**db_info)

      3、建立游标:conn.cursor(pymysql.cursors.DictCursor)

      4、执行sql:execute(sql)

    2、写入excel

      1、book = xlwt.Workbook()

       sheet = book.add_sheet('sheet1')

      2、sheet.write()

 1 import pymysql,xlwt
 2 def op_mysql(sql,many=True):
 3     db_info = {'user': 'xmb', 'password': '123456', 'host': '127.0.0.0', 'db': 'xmb', 'port': 3306,
 4                'charset': 'utf8', 'autocommit': True}
 5     try:
 6         conn = pymysql.connect(**db_info)  #建立连接
 7     except Exception as e:
 8         print("数据库连接失败",e)
 9         return "数据库连接失败"
10     cur = conn.cursor(pymysql.cursors.DictCursor)  #建立游标
11     try:
12         cur.execute(sql)  #执行sql
13     except Exception as e:
14         print("sql错误,%s"%sql)
15         result = "sql错误,%s"%sql
16     else:
17         if many:
18             result = cur.fetchall()  #fetchall返回的是列表
19         else:
20             result = cur.fetchone()  #fetchone返回的是字典
21     finally:
22         cur.close()
23         conn.close()
24     return result
25 
26 def export_excel(table_name):
27     sql = 'select *  from %s'%table_name
28     result = op_mysql(sql)
29     if result:
30         file_name = '%s.xls'%table_name
31         book = xlwt.Workbook()
32         sheet = book.add_sheet('sheet1')
33         for col,k in enumerate(result[0]):  #写表头
34             sheet.write(0,col,k)
35         for row,row_data in enumerate(result,1):   #控制行
36             for col,col_data in enumerate(row_data.values()):  #控制列,.values()是获取字典里的所有values
37                 sheet.write(row,col,col_data)
38             book.save(file_name)
39     else:
40         print('表数据为空')
41 
42 export_excel('app_myuser')

 

posted @ 2019-11-19 17:10  xmb  阅读(144)  评论(0)    收藏  举报