Python操作数据库及excel练习一_将数据库表中的数据导出到excel中

需求:

将数据库表中的数据导出到excel中

循环控制行和列的写入

实现:

import pymysql,xlwt

def conn_db(sql,host='xxx.xxx.x.xx',user='xx',passwd='123456',db='xx',port=3306,charset = 'utf8'):
    conn = pymysql.connect(user=user,host=host,passwd=passwd,db=db,port=port,charset=charset)
    cur = conn.cursor()
    cur.execute(sql)
    res = cur.fetchall()
    cur.close()
    conn.close()
    return res

all_stu = conn_db('select * from stu')#获取数据库表数据
book = xlwt.Workbook()
sheet = book.add_sheet('学生信息')
sheet.write(0,0,'编号')
sheet.write(0,1,'姓名')
sheet.write(0,2,'性别')
row = 1#记录中编号有重复,用all_stu.index[i]+1会报错
for i in all_stu:
    for j in i:
        column = i.index(j)
        sheet.write(row,column,j)
    row += 1
book.save('学生信息.xls')

优化代码:

表头循环写入

titles = ['编号','姓名','性别']
column = 0#
for t in titles:
    sheet.write(0,column,t)#写表头
    column += 1

通过指定游标返回类型cursor=pymysql.cursors.DictCursor,优化表头写入

原文地址:https://www.cnblogs.com/dongrui624/p/9002340.html