美文网首页
将Excel数据写入到mysql

将Excel数据写入到mysql

作者: overad | 来源:发表于2018-09-04 09:22 被阅读0次
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/9/3 14:51
# @File : excel2mysql
# @Software: PyCharm

import pymysql
import xlrd
import datetime

start = datetime.datetime.now()
print(start)
#链接mysql
conn = pymysql.connect(host='localhost',user='root',passwd='12345',db='ss ',port=3306,charset='utf8')
cursor = conn.cursor()

#读取Excel
wb = xlrd.open_workbook('D:\\ex2\\car_total.xlsx')
sh = wb.sheet_by_index(0)

#标题:
title = sh.row_values(0)
extime = datetime.datetime.now()
print("读取表格:{}".format(extime - start))
#行数
nrows =sh.nrows
#列数
ncols = sh.ncols

#准备一个list,存放excel中的内容
df_1 = []

for i in range(nrows):
    #不能包含表头
    if i == 0:
        continue
    df_1.append(sh.row_values(i))


#创建表:不能直接放在循环里面是因为会重复创建表
cursor.execute("create table car_total (  " + title[0] + " varchar(100)) engine ='Innodb' charset ='utf8';" )

#为创建的表添加属性:
for i in range(1,ncols):
    cursor.execute("alter table car_total add " + title[i] + " varchar(200);")

#创建插入的insert into table values后面的占位符
val = ''
for i in range(ncols):
    val = val + '%s,'


try:
    cursor.executemany("insert into car_total values(" + val[:-1] +" );",df_1)

except Exception as e:
    print(e)

cursor.close()
conn.commit()
conn.close()
#print(sh.row_values(0))
end = datetime.datetime.now()
print("运行时间:{}".format((end-start)))

相关文章

网友评论

      本文标题:将Excel数据写入到mysql

      本文链接:https://www.haomeiwen.com/subject/ykowwftx.html