发布网友 发布时间:2022-04-22 00:15
共2个回答
懂视网 时间:2022-05-03 08:57
root‘,host=‘127.0.0.1‘,port=3306,passwd=‘root‘,db=‘python‘,charset=‘utf8‘) #连接数据库 cur = conn.cursor()2、读取mysql数据库中表数据
1 sql = ‘select * from %s;‘ %table_name #需要写入excel表数据 2 #读取数据 3 cur.execute(sql) #读取数据 4 fileds = [filed[0] for filed in cur.description] #读取表结构定义 5 all_date = cur.fetchall() #所有数据 6 for result in all_date: 7 print(result) 8
3、数据写入excel
1 book = xlwt.Workbook() #创建一个book 2 3 sheet = book.add_sheet(‘result‘) #创建一个sheet表 4 5 for col,filed in enumerate(fileds): 6 sheet.write(0,col,filed) #将表字段描述写入excel第一行 7 8 #从第一行开始写 9 10 row = 1 11 for data in all_date: 12 for col,filed in enumerate(data): 13 sheet.write(row,col,filed)#将数据写入excel单元格中 14 row += 1
4、保存excel
book.save(‘%s.xls‘ %table_name)
5、完整代码
#!/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读取数据,写入excel中 ‘‘‘ import pymysql,xlwt def export_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 in cur.description] all_date = cur.fetchall() #所有数据 for result in all_date: print(result) #写excel book = xlwt.Workbook() #创建一个book sheet = book.add_sheet(‘result‘) #创建一个sheet表 for col,filed in enumerate(fileds): sheet.write(0,col,filed) #从第一行开始写 row = 1 for data in all_date: for col,filed in enumerate(data): sheet.write(row,col,filed) row += 1 book.save(‘%s.xls‘ %table_name) if __name__ == ‘__main__‘: export_excel(‘stocks‘)
python读取数据库表数据并写入excel
标签:单元格 ble print 开始 pre excel fetch har sele
热心网友 时间:2022-05-03 06:05
读取mysql数据,填写数据到excel