99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python實現(xiàn)將數(shù)據(jù)庫一鍵導出為Excel表格的實例
Python實現(xiàn)將數(shù)據(jù)庫一鍵導出為Excel表格的實例
2017-09-14
收藏

Python實現(xiàn)將數(shù)據(jù)庫一鍵導出為Excel表格的實例

下面小編就為大家?guī)硪黄?a href="http://www.3lll3.cn/view/22818.html" target="_blank">Python實現(xiàn)將數(shù)據(jù)庫一鍵導出為Excel表格的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,

數(shù)據(jù)庫數(shù)據(jù)導出為excel表格,也可以說是一個很常用的功能了。畢竟不是任何人都懂數(shù)據(jù)庫操作語句的。

下面先來看看完成的效果吧。

數(shù)據(jù)源

導出結(jié)果

依賴
由于是Python實現(xiàn)的,所以需要有Python環(huán)境的支持

Python2.7.11

我的Python環(huán)境是2.7.11。雖然你用的可能是3.5版本,但是思想是一致的。

xlwt
pip install xlwt

MySQLdb
pip install MySQLdb

如果上述方式不成功的話,可以到sourceforge官網(wǎng)上去下載windows上的msi版本或者使用源碼自行編譯。

數(shù)據(jù)庫相關(guān)

本次試驗,數(shù)據(jù)庫相關(guān)的其實也就是如何使用Python操作數(shù)據(jù)庫而已,知識點也很少,下述為我們本次用到的一些簡單的語句。

連接

conn = MySQLdb.connect(host='localhost',user='root',passwd='mysql',db='test',charset='utf8')

這里值得我們一提的就是最后一個參數(shù)的使用,不然從數(shù)據(jù)庫中取出的數(shù)據(jù)就會使亂碼。關(guān)于亂碼問題,如果還有不明白的地方,不妨看下這篇文章 淺談編碼,解碼,亂碼的問題

獲取字段信息    
fields = cursor.description

至于cursor,是我們操作數(shù)據(jù)庫的核心。游標的特點就是一旦遍歷過該條數(shù)據(jù),便不可返回。但是我們也可以手動的改變其位置。

cursor.scroll(0,mode='absolute')來重置游標的位置

獲取數(shù)據(jù)

獲取數(shù)據(jù)簡直更是輕而易舉,但是我們必須在心里明白,數(shù)據(jù)項是一個類似于二維數(shù)組的存在。我們獲取每一個cell項的時候應該注意。    
results = cursor.fetchall()

Excel基礎

同樣,這里講解的也是如何使用Python來操作excel數(shù)據(jù)。

workbook

工作薄的概念我們必須要明確,其是我們工作的基礎。與下文的sheet相對應,workbook是sheet賴以生存的載體。    
workbook = xlwt.Workbook()

sheet

我們所有的操作,都是在sheet上進行的。

sheet = workbook.add_sheet(‘table_message',cell_overwrite_ok=True)

對于workbook 和sheet,如果對此有點模糊。不妨這樣進行假設。

日常生活中記賬的時候,我們都會有一個賬本,這就是workbook。而我們記賬則是記錄在一張張的表格上面,這些表格就是我們看到的sheet。一個賬本上可以有很多個表格,也可以只是一個表格。這樣就很容易理解了吧。 :-)

案例

下面看一個小案例。    
# coding:utf8
import sys
 
reload(sys)
sys.setdefaultencoding('utf8')
# __author__ = '郭 璞'
# __date__ = '2016/8/20'
# __Desc__ = 從數(shù)據(jù)庫中導出數(shù)據(jù)到excel數(shù)據(jù)表中
 
import xlwt
import MySQLdb
 
conn = MySQLdb.connect('localhost','root','mysql','test',charset='utf8')
cursor = conn.cursor()
 
count = cursor.execute('select * from message')
print count
# 重置游標的位置
cursor.scroll(0,mode='absolute')
# 搜取所有結(jié)果
results = cursor.fetchall()
 
# 獲取MYSQL里面的數(shù)據(jù)字段名稱
fields = cursor.description
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('table_message',cell_overwrite_ok=True)
 
# 寫上字段信息
for field in range(0,len(fields)):
 sheet.write(0,field,fields[field][0])
 
# 獲取并寫入數(shù)據(jù)段信息
row = 1
col = 0
for row in range(1,len(results)+1):
 for col in range(0,len(fields)):
  sheet.write(row,col,u'%s'%results[row-1][col])
 
workbook.save(r'./readout.xlsx')

封裝

為了使用上的方便,現(xiàn)將其封裝成一個容易調(diào)用的函數(shù)。

封裝之后    
# coding:utf8
import sys
 
reload(sys)
sys.setdefaultencoding('utf8')
# __author__ = '郭 璞'
# __date__ = '2016/8/20'
# __Desc__ = 從數(shù)據(jù)庫中導出數(shù)據(jù)到excel數(shù)據(jù)表中
 
import xlwt
import MySQLdb
 
def export(host,user,password,dbname,table_name,outputpath):
 conn = MySQLdb.connect(host,user,password,dbname,charset='utf8')
 cursor = conn.cursor()
 
 count = cursor.execute('select * from '+table_name)
 print count
 # 重置游標的位置
 cursor.scroll(0,mode='absolute')
 # 搜取所有結(jié)果
 results = cursor.fetchall()
 
 # 獲取MYSQL里面的數(shù)據(jù)字段名稱
 fields = cursor.description
 workbook = xlwt.Workbook()
 sheet = workbook.add_sheet('table_'+table_name,cell_overwrite_ok=True)
 
 # 寫上字段信息
 for field in range(0,len(fields)):
  sheet.write(0,field,fields[field][0])
 
 # 獲取并寫入數(shù)據(jù)段信息
 row = 1
 col = 0
 for row in range(1,len(results)+1):
  for col in range(0,len(fields)):
   sheet.write(row,col,u'%s'%results[row-1][col])
 
 workbook.save(outputpath)
 
 
# 結(jié)果測試
if __name__ == "__main__":
 export('localhost','root','mysql','test','datetest',r'datetest.xlsx')

測試結(jié)果    
id name date
1 dlut 2016-07-06
2 清華大學 2016-07-03
3 北京大學 2016-07-28
4 Mark 2016-08-20
5 Tom 2016-08-19
6 Jane 2016-08-21
總結(jié)
回顧一下,本次試驗用到了哪些知識點。
?Python簡易操作數(shù)據(jù)庫
?Python簡易操作Excel
?數(shù)據(jù)庫取出數(shù)據(jù)亂碼問題解決之添加charset=utf-8
?以二維數(shù)組的角度來處理獲取到的結(jié)果集。
以上這篇Python實現(xiàn)將數(shù)據(jù)庫一鍵導出為Excel表格的實例就是小編分享給大家的全部內(nèi)容了

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }