|
楼主 |
发表于 2022-6-19 17:13:48
|
显示全部楼层
四、用pandas读取excel内容,批量写入MySQL数据库
excel表格格式和数据库一致,读取的时候忽略表头
- import pandas as pd
- df = pd.read_excel("001.xlsx", engine="openpyxl", sheet_name="Sheet1")
- import pymysql
- host = 'localhost'
- port = 3308
- user = 'root'
- psd = '123456'
- db = 'faren'
- charset = 'utf8'
- db = pymysql.Connect(host=host,port=port,user=user,passwd=psd,db=db,charset=charset)
- print('OK')
- cursor = db.cursor()
- for i in range(0,len(df)):
- row_data = df.loc[[i]].values
- for cell in row_data:
- id = cell[0]
- name = cell[1]
- age = cell[2]
- sql = "insert into test values(" + str(id) + ",'" + name + "'," + str(age) + ");"
- cursor.execute(sql)
- db.commit()
- cursor.close()
- db.close()
复制代码 完成后,查看数据库,如下图:
|
|