'''
将数据库表格导入excel
思路:
1、先连接数据库
2、传入一个表名,将数据获取到
3、写入excel
'''
import pymysql,xlwt
info={
'host':"118.24.30.401",
"user":'gggz',
"password":'1khgf6',
'port':3306,
"db":'gggz'
}
#连接数据库,获取数据
def connect_mysql(table_name):
conn = pymysql.connect(**info)
cur = conn.cursor()
try:
cur.execute('select * from %s limit 10;'%table_name)
except Exception as e:
res={"error_code":0,"error_msg":e.args}
return res
else:
res = list(cur.fetchall())
#获取表头:
fields = [field[0] for field in cur.description] #cur.description表示获取表头字段
res.insert(0,fields)
cur.close()
conn.close()
return res
#写入excel
def write_to_excel(table_name):
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
try:
res = connect_mysql(table_name)
except Exception as e:
print('数据未获取成功')
else:
#处理从数据表中读取到得数据
for index,value in enumerate(res):#先获取到每一个大得列表
for index2 ,value2 in enumerate(value): #获取每一个小得列表的内容,真正要写入的内容,行不变,列在改变。嵌套循环
sheet.write(index,index2,value2)
book.save('%s.xls'%table_name)
print('导入成功')
if __name__ == '__main__':
write_to_excel('app_myuser')