python从数据库取数据保存为excel_python读取数据库表数据并写入excel
#!/usr/bin/env python#-*- coding: utf-8 -*-
'''@Time : 2020/1/1 18:08
@Author : Jason.Jia
@contact: jiajunp@163.com
@Version : 1.0
@file :mysql_write_excel.py
@desc :
從mysql讀取數(shù)據(jù),寫入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#讀取數(shù)據(jù)
cur.execute(sql)
fileds= [filed[0] for filed incur.description]
all_date= cur.fetchall() #所有數(shù)據(jù)
for result inall_date:print(result)#寫excel
book= xlwt.Workbook() #創(chuàng)建一個book
sheet= book.add_sheet('result') #創(chuàng)建一個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')
總結(jié)
以上是生活随笔為你收集整理的python从数据库取数据保存为excel_python读取数据库表数据并写入excel的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python opencv 界面按钮_P
- 下一篇: 移动**21*设置无法接通_电话打得出去