师从‘百测’besttest
最近牛大湿教了操作数据库和操作excel,写了一个小小的脚本,传入一个表名后,将表中所有数据写入excel中。
使用了pymysql,xlwt,需要自行安装。
import pymysql,xlwt def sql_into_excel(table_name): db_info = {‘user‘: ‘xxx‘, ‘password‘: ‘123456‘,‘host‘: ‘8.8.8.8‘, ‘db‘: ‘asd‘, ‘port‘: 3306, ‘charset‘: ‘utf8‘,‘autocommit‘: True} conn = pymysql.connect(**db_info) # 建立连接 cur = conn.cursor(pymysql.cursors.DictCursor) #获取表头的游标 sql = ‘select * from %s‘ %(table_name) #如果参数在实际查询中需要用‘’,在SQL中写法:‘%s‘ cur.execute(sql) all = cur.fetchall() cur.close() conn.close() key = [] for i in all[0]: key.append(i) book = xlwt.Workbook() sheet = book.add_sheet(‘sheet1‘) for j in range(len(key)): sheet.write(0,j,key[j]) for x in range(len(all)): a = key[j] sheet.write(x 1,j,all[x][a]) book.save(‘test.xls‘) sql_into_excel(‘table_name‘)