200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python从数据库取数据保存为excel_python读取数据库表数据并写入excel

python从数据库取数据保存为excel_python读取数据库表数据并写入excel

时间:2024-05-15 11:34:44

相关推荐

python从数据库取数据保存为excel_python读取数据库表数据并写入excel

#!/usr/bin/env python#-*- coding: utf-8 -*-

'''@Time : /1/1 18:08

@Author : Jason.Jia

@contact: jiajunp@

@Version : 1.0

@file :mysql_write_excel.py

@desc :

从mysql读取数据,写入excel中'''

importpymysql,xlwtdefexport_excel(table_name):

conn= pymysql.connect(user='root',host='127.0.0.1',port=3306,passwd='root',db='python',charset='utf8')

cur=conn.cursor()

sql= 'select * from %s;' %table_name#读取数据

cur.execute(sql)

fileds= [filed[0] for filed incur.description]

all_date= cur.fetchall() #所有数据

for result inall_date:print(result)#写excel

book= xlwt.Workbook() #创建一个book

sheet= book.add_sheet('result') #创建一个sheet表

for col,filed inenumerate(fileds):

sheet.write(0,col,filed)#从第一行开始写

row= 1

for data inall_date:for col,filed inenumerate(data):

sheet.write(row,col,filed)

row+= 1book.save('%s.xls' %table_name)if __name__ == '__main__':

export_excel('stocks')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。