PYTHON实现EXCEL数据导入MYSQL

# coding=utf8
import pymysql
import os
import pandas as pd

host='127.0.0.1'
port=3308
user='root'
password='*****'
db='impairment_testing'

conn=pymysql.connect(host=host,port=port,user=user,password=password,db=db)
cursor=conn.cursor()

# 指定拟导入EXCEL文件路径,根据需要更换路径。
file_path=r'C:\Users\user\Desktop\ModelDesigning\impairment_testing\excel_data'

files=[]
table_names=[]
for filename in os.listdir(file_path):
    if filename.endswith((".xlsx") or filename.endswith(".xls")): #确保是Excel文件
        file=os.path.join(file_path,filename)
        table_names.append(os.path.splitext(filename)[0])
        files.append(file)
# print(files)
print(table_names)

#构建数据表结构,结构与需要导入的EXCEL文件保持一致!!!
table_data = [
    {
        "table_name": table_names[0],
        "columns": [
            {"name": "date", "type": "DATE"},
            {"name": "price", "type": "DECIMAL(10,2)"},
        ]
    },
    {
        "table_name": table_names[1],
        "columns": [
            {"name": "date", "type": "DATE"},
            {"name": "value", "type": "DECIMAL(10,0)"},
        ]
    },
]

# 遍历列表,根据表名和列名创建表和列
for table in table_data:
    table_name = table["table_name"]
    columns = ", ".join([f"{col['name']} {col['type']}" for col in table["columns"]])
    #先删除原有数据表
    drop_table=f'drop table if exists {table_name} '
    creat_table_query = f"""        
        CREATE TABLE {table_name}(  
            {columns}  
        )  
    """
    cursor.execute(drop_table)
    cursor.execute(creat_table_query)

    # cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
    # # 判断表是否存在
    # if cursor.fetchone():
    #     print(f"Table {table_name} exists")
    # # 如果不存在则创建表
    # else:
    #     cursor.execute(creat_table_query)
    #     print(f"Table {table_name} created.")

for file in files:
    filename = os.path.basename(file)  # 获取文件名,即表名,文件名与表名必须保持一致。

    # 检查文件名的后缀名
    suffix = filename.split('.')[-1]

    # 根据后缀名来决定如何截取文件名以获取表名
    if suffix == 'xlsx':
        table_name = filename[:-5]  # 如果是.xlsx,去掉".xlsx"后缀
    elif suffix == 'xls':
        table_name = filename[:-4]  # 如果是.xls,去掉".xls"后缀
    else:
        print(f"Unknown file format: {filename}")  # 如果不是.xlsx或.xls,打印错误信息

    # print(table_name)

    df = pd.read_excel(file)  # 读取Excel文件的数据到DataFrame中
    # print(df)
    # df.to_sql(table_name,con=conn,if_exists='replace',index=False) #要求conn必须是sqlAlchemy引擎,弃用。

    #通过遍历df行列形式将EXCEL数据导入MYSQL
    for index,row in df.iterrows():
        values=[row[col] for col in df.columns]# 构建要插入的值的列表
        # print(values)
        sql = f"INSERT INTO {table_name} VALUES ({','.join(['%s' for _ in df.columns])});"  # SQL语句,用于导入数据到对应的表中,注意修改分隔符以匹配你的数据格式
        # print(sql)
        cursor.execute(sql,values)  # 执行SQL语句,导入数据到对应的表中
    # sql = "INSERT INTO brent_price (date0,price) VALUES ('2023-8-1',80);"
    # cursor.execute(sql)  # 执行SQL语句,导入数据到对应的表中
    print(f"Data loaded into table {table_name}")

conn.commit()
cursor.close()
conn.close()

1. EXCEL文件名与数据表同名,结构保持一致。

posted @ 2023-11-24 15:18  汶淏  阅读(363)  评论(0)    收藏  举报