一、环境准备,安装包
pip install pandas openpyxl sqlalchemy
二、数据准备
三、代码编写
from sqlalchemy import create_engine
import pandas as pdclass GDPDataImporter:def __init__(self, db_type, dbapi, host, port, database, username, password):"""初始化数据库连接参数:param db_type: 数据库类型,如 'mysql', 'mssql+pyodbc', 'postgresql' 等:param dbapi: 数据库API,如 'pymysql' 对于MySQL:param host: 数据库主机地址:param port: 数据库端口:param database: 数据库名:param username: 数据库用户名:param password: 数据库密码"""self.engine = create_engine(f"{db_type}+{dbapi}://{username}:{password}@{host}:{port}/{database}")def import_data(self, excel_file_path, table_name):"""从Excel文件导入数据到数据库:param excel_file_path: Excel文件的路径:param table_name: 数据库中的表名"""try:df = pd.read_excel(excel_file_path)df.to_sql(name=table_name, con=self.engine, if_exists='replace', index=False)print("数据导入成功!")except Exception as e:print(f"数据导入失败: {e}")
if __name__ == "__main__":importer = GDPDataImporter(db_type='mysql',dbapi='pymysql',host='localhost',port='3306',database='world',username='root',password='123456')excel_file_path = r'F:\省会城市总、人均GDP.xlsx'importer.import_data(excel_file_path, 'GDP')
四、查看表数据