有上百个表格文件(需要表格表头与数据表的表头一致),需要同时导入到数据库中的某一张表里,人工手动会很累
import os
import pandas as pd
import pymysql
from openpyxl import load_workbook
# 修改为你的MySQL数据库连接信息
host = 'localhost'
user = 'root'
password = '123456'
database = 'shujuku'
# 遍历文件夹下的所有Excel文件
folder_path = '' # 文件目录路径
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 连接到MySQL数据库
connection = pymysql.connect(host=host, user=user, password=password, database=database)
cursor = connection.cursor()
# 你指定的表名
specified_table_name = ''
# 遍历Excel文件并导入数据到MySQL数据库的指定表中
for file in excel_files:
file_path = os.path.join(folder_path, file)
wb = load_workbook(file_path)
ws = wb.active
# 遍历工作表中的所有行,将数据插入到MySQL数据库的指定表中
for row in ws.iter_rows(min_row=2, values_only=True): # 假设第一行是表头,从第二行开始插入数据
placeholders = ', '.join(['%s'] * len(row))
sql = f"INSERT INTO {specified_table_name} VALUES ({placeholders})"
cursor.execute(sql, row)
print(file)
# 提交事务并关闭连接
connection.commit()
cursor.close()
connection.close()
批量表格文件导入数据库
806

被折叠的 条评论
为什么被折叠?



