Python将Excel表的数据导入到PostgreSQL数据库中
安装依赖包
pip3 install sqlalchemy psycopg2 pandas openpyxl
Excel表student.xlsx
的数据如下
数据库中存在一张表名为student
,字段有name
、sex
、height
、weight
的表
导入Excel数据到数据库的代码如下
import pandas as pd
from sqlalchemy import create_engine
USERNAME = "postgres" # 用户名
PASSWORD = "123456" # 密码
HOST = "localhost" # IP
PORT = 5432 # 端口
DB = 'myclass' # 数据库
TABLE = 'student' # 数据表
ENGINE_CONFIG = f'postgresql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DB}' # 连接postgresql引擎配置
conn = create_engine(ENGINE_CONFIG)
col_name = ['name', 'sex', 'height', 'weight'] # 与数据表字段名称保持一致
df = pd.read_excel('student.xlsx', names=col_name)
print(df.head())
df.to_sql(TABLE, conn, if_exists='append', index=False) # if_exists的值为append表示追加,为replace表示替换