python脚本实现excel和mysql数据库表的导入导出

 

excel到mysql数据库表(仅支持.xlsx格式导入):

#!/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)
conn.commit()

mysql数据库表到excel(仅支持.xlsx格式导出):

#!/usr/bin/env python  
#coding=utf-8  
import xlwt  
import MySQLdb  
conn=MySQLdb.connect(host='localhost',user='root',passwd='××××',db='test')  
cursor=conn.cursor()  
count = cursor.execute('select * from test1')  
print 'has %s record' % count  
#重置游标位置  
cursor.scroll(0,mode='absolute')  
#搜取所有结果  
results = cursor.fetchall()  
#测试代码,print results  
#获取MYSQL里的数据字段  
fields = cursor.description  
#将字段写入到EXCEL新表的第一行  
wbk = xlwt.Workbook()  
sheet = wbk.add_sheet('test1',cell_overwrite_ok=True)  
for ifs in range(0,len(fields)):  
    sheet.write(0,ifs,fields[ifs][0])  
ics=1  
jcs=0  
for ics in range(1,len(results)+1):  
    for jcs in range(0,len(fields)):  
        sheet.write(ics,jcs,results[ics-1][jcs])  
wbk.save('×××××/Desktop/test4.xlsx')  

猜你喜欢

转载自blog.csdn.net/myli_binbin/article/details/85132233