原文地址:http://blog.kantli.com/article/46
在頁(yè)面上導(dǎo)出數(shù)據(jù)是常見(jiàn)的需求邮偎,在flask中肌似,要導(dǎo)出excel格式的數(shù)據(jù)讯赏,可以使用xlwt庫(kù)垮兑,創(chuàng)建excel文件,逐行寫(xiě)入漱挎,不過(guò)系枪,tablib庫(kù)對(duì)這種操作做了很好的封裝,用起來(lái)會(huì)更簡(jiǎn)單一些磕谅。
tablib可以通過(guò)pip直接安裝私爷。
tablib的使用,首先是構(gòu)建基本數(shù)據(jù)對(duì)象:
import tablib
data = tablib.Dataset(*dataList, headers=headerList)
其中dataList是數(shù)據(jù)列表膊夹,一般是根據(jù)數(shù)據(jù)庫(kù)查詢(xún)結(jié)果構(gòu)建的衬浑,列表中是每行數(shù)據(jù)的列表,例如:
[[1,2,3], [4,5,6], [7,8,9]]
headerList是標(biāo)題列表放刨,一般手動(dòng)構(gòu)建嚎卫,例如:
[U'第一列', U'第二列', U'第三列']
獲取數(shù)據(jù)對(duì)象之后,可以根據(jù)這個(gè)對(duì)象生成各種格式的數(shù)據(jù)文件宏榕,可以保存在服務(wù)器上供人下載拓诸,或者直接生成請(qǐng)求的響應(yīng)。不需要多次下載的情況下麻昼,直接生成響應(yīng)比較簡(jiǎn)單:
from flask import make_response
resp = make_response(data.xls)
filename = 'filename.xls' #用戶(hù)下載默認(rèn)文件名
resp.headers["Content-Disposition"] = "attachment; filename=" + filename #指定響應(yīng)為下載文件
resp.headers['Content-Type'] = 'xls' #不指定的話會(huì)默認(rèn)下載html格式奠支,下載后還要改格式才能看
return resp
那么,一個(gè)綜合的例子如下抚芦,根據(jù)用戶(hù)給定的時(shí)間區(qū)間導(dǎo)出數(shù)據(jù):
@main.route('/export_data', methods=['GET', 'POST'])
def export_data():
form = ExportDataForm() #供用戶(hù)指定時(shí)間的表格倍谜,在forms中創(chuàng)建的簡(jiǎn)單類(lèi)迈螟,導(dǎo)入使用
if form.validate_on_submit():
startDate = form.startDate.data
endDate = form.endDate.data
dataList = getData(startDate=startDate, endDate=endDate) #查詢(xún)數(shù)據(jù)庫(kù)并返回列表的函數(shù),在其它文件創(chuàng)建并導(dǎo)入這里使用
headerList = [U"核導(dǎo)彈代碼", U"類(lèi)別", U"生產(chǎn)單位", U"入庫(kù)日期"]
data = tablib.Dataset(*dataList, headers=headerList)
resp = make_response(data.xls)
resp.headers['Content-Type'] = 'xls'
filename = "核武庫(kù)" + startDate.strftime("%Y%m%d") + "-" + endDate.strftime("%Y%m%d") + ".xls"
resp.headers["Content-Disposition"] = "attachment; filename=" + filename
return resp
return render_template('export_data.html', form=form)