源码:
环境:win7
#!/usr/bin/python
#coding:gbk
print "你好"
import xlrd
import MySQLdb
import os
for fpathe,dirs,fs in os.walk("C:\\AAA\\python\\test4\\"):
for f in fs:
print os.path.join(fpathe,f)
filename = os.path.join(fpathe,f)
#读取EXCEL中内容到数据库中
#for j in subjects:
# print j
# print "我的"
wb = xlrd.open_workbook(filename)
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='user',passwd='password',db='my_schema')
cursor=conn.cursor()
conn.set_character_set('utf8') #设置导入mysql的字符,防止乱码产生
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET NAMES utf8;')
cursor.execute('SET character_set_connection=utf8;')
#创建table
#cursor.execute("create table test4("+fo[0][0]+" varchar(100));")
#cursor.execute("truncate table data;")
#创建table属性
#for i in range(1,ncols):
# cursor.execute("alter table data add "+fo[0][i]+" varchar(100);")
val=''
for i in range(0,ncols):
val = val+'%s,'
print dfun
if (ncols == 20):
cursor.executemany("insert into data20 values("+val[:-1]+");" ,dfun)
elif (ncols == 21):
cursor.executemany("insert into data21 values("+val[:-1]+");" ,dfun)
elif (ncols == 22):
cursor.executemany("insert into data22 values("+val[:-1]+");" ,dfun)
else:
print "有问题"
conn.commit()