1. 程式人生 > >python指令碼實現excel和mysql資料庫表的匯入匯出

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')