python 将mysql数据库信息写入xlsx

使用openpyxl库

from openpyxl import Workbook
import pymysql

con = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="***", db="student",charset="utf8")
cur = con.cursor()
cur.execute("use student")


def sql_excel():
    wb = Workbook()
    ws = wb.active
    ws.title = "test"
    sql = "select * from student"
    cur.execute(sql)
    #description 获取字段信息
    #(('id', 3, None, 11, 11, 0, False), ('name', 253, None, 20, 20, 0, False))
    for i in range(1, len(cur.description)+1):
        ws.cell(row=1, column=i, value=cur.description[i - 1][0])
    for row in range(2, cur.rowcount + 2):
        #fetchone 数据库具体信息 (1, '张三', '男', 1)
        ws.append(cur.fetchone())
    wb.save("student.xlsx")


try:
    sql_excel()
except Exception as e:
    raise e
finally:
    cur.close()
    con.close()

 

上一篇:华为视频编辑服务(Video Editor Kit),助力开发者高效构建应用视频编辑能力


下一篇:工业基础类IFC—IFC Viewers