import pandas as pd import pymysql # 打开Excel文档 file_path = r'D:\***.xlsx' # 读取一个表单 df = pd.read_excel(file_path, sheet_name="Sheet1") # 打开数据库连接 db = pymysql.connect(host='localhost', user='root', passwd='******', db='database_name') # 使用cursor()方法获取操作游标 cursor = db.cursor() i = 0 # while循环读行数据 while i < df.shape[0]: # 建一个空列表 list = [] j=0 # 嵌套while循环读行中每个数据,写入列表 while j < df.shape[1]: # 判断如果是空值,则往列表中写入"None" if pd.isna(df.loc[i][j]): list.append(None) else: list.append(df.loc[i][j]) j += 1 # 创建数据表SQL语句 sql = """INSERT INTO table_name(No,data1,data2) VALUES (%s,%s,%s)""" cursor.execute(sql,(i,list[0],list[1])) i += 1 db.commit() cursor.close() # 关闭数据库连接 db.close()
Python Excel to mysql, pandas “None” 空值报错问题处理
最新推荐文章于 2024-04-29 21:50:55 发布