python指令碼實現excel到mysql資料庫表(僅支援.xlsx格式匯入)
阿新 • • 發佈:2019-01-30
#!/usr/bin/env python
#coding=utf-8
import xlrd
import MySQLdb
#讀取EXCEL中內容到資料庫中
wb = xlrd.open_workbook('/×.xlsx')
sh = wb.sheet_by_index(0)
dfun=[]
nrows = sh.nrows #行數
ncols = sh.ncols #列數
fo=[]
fo.append(sh.row_values(0))
for i in range(1,nrows):
dfun.append(sh.row_values(i))
conn=MySQLdb.connect(host='localhost',user='root',passwd='××××××',db='db')
cursor=conn.cursor()
#建立table
cursor.execute("create table test4("+fo[0][0]+" varchar(100));")
#建立table屬性
for i in range(1,ncols):
cursor.execute("alter table test4 add "+fo[0][i]+" varchar(100);")
val=''
for i in range(0,ncols):
val = val+'%s,'
print dfun
cursor.executemany("insert into resources_networkdevice values("+val[:-1]+");" ,dfun)
#coding=utf-8
import xlrd
import MySQLdb
#讀取EXCEL中內容到資料庫中
wb = xlrd.open_workbook('/×.xlsx')
sh = wb.sheet_by_index(0)
dfun=[]
nrows = sh.nrows #行數
ncols = sh.ncols #列數
fo=[]
fo.append(sh.row_values(0))
for i in range(1,nrows):
dfun.append(sh.row_values(i))
conn=MySQLdb.connect(host='localhost',user='root',passwd='××××××',db='db')
cursor=conn.cursor()
#建立table
cursor.execute("create table test4("+fo[0][0]+" varchar(100));")
#建立table屬性
for i in range(1,ncols):
cursor.execute("alter table test4 add "+fo[0][i]+" varchar(100);")
val=''
for i in range(0,ncols):
val = val+'%s,'
print dfun
cursor.executemany("insert into resources_networkdevice values("+val[:-1]+");" ,dfun)
conn.commit()