excel数据格式:
import pandas as pd
import xlrd
import xlwt
import pymysql
df=pd.read_excel('1.xlsx')
#总行数 len(df)
nums = df.shape[0]
#数据清洗nan默认为0
df.fillna(0, inplace= True)
#删除第一行无用数据
ds = df.drop(index=[0,0])
nums = nums - 1
#数据库操作
class MysqlAct(object):
def __init__(self):
self.connect = pymysql.connect('localhost', 'root', 'root', 'appjjr', use_unicode=True, charset='utf8')
self.cursor = self.connect.cursor()
def __del__(self):
self.connect.close()
def select(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchall()
def insert(self, sql):
self.cursor.execute(sql)
self.connect.commit()
if __name__ == '__main__':
#获取表结构
mysql = MysqlAct()
sql = "select COLUMN_NAME from information_schema.columns where table_schema='appjjr' and table_name='fcxlt_count_pvuv'"
fields = mysql.select(sql)
fieldsli = []
for i in fields:
fieldsli.append(i[0])
fieldsli.remove('id')
fieldsli = str(tuple(fieldsli)).replace("'", '')
print("表结构是:{}".format(fieldsli))
#数据处理
for i in range(nums):
#获取行数据转列表
row = ds.loc[i+1].tolist()
row[0] = str(row[0])
rowdata = tuple(row)
sql = "insert into fcxlt_count_pvuv %s VALUES %s" % (fieldsli, rowdata)
mysql.insert(sql)
print('新增数据:{}'.format(rowdata))