Python将数据库的数据导出为Excel

本文使用pandas来获取数据库的数据并生成Excel表格,以下用PostgreSQL数据库为例

安装第三方库

pip3 install sqlalchemy psycopg2 pandas openpyxl

数据库中有student数据表,如下

id name age sex
1 Tony 18 male
2 Jane 16 female
3 Jack 15 male

导出excel表的代码如下

import pandas as pd
from sqlalchemy import create_engine

# engine = create_engine('dialect+driver://username:password@host:port/database')
engine = create_engine('postgresql://postgres:111111@localhost:5432/mydb')

sql = "SELECT * FROM student"

df = pd.read_sql(sql, engine)
print(df.head())

df.to_excel('student.xlsx', index=None)

导出的student.xlsx表内容如下

student

posted @ 2022-04-29 10:22  蓝莓薄荷  阅读(2639)  评论(0编辑  收藏  举报