1. 程式人生 > 其它 >django xlwt excel資料匯出

django xlwt excel資料匯出

最近在寫主機管理並支援遠端命令執行,返回結果以execl表格形式顯示,涉及到execl表格的下載問題。網上大部分都是python2的部分的程式碼,我執行的環境是python3下,

經過測試和修改,該了部分程式碼。

首先我們先了解幾個概念:

1、content_type='application/vnd.ms-excel':該引數是告訴瀏覽器,傳輸的檔案是什麼型別檔案。要以什麼方式進行處理。

2、Content-Disposition=‘attachment;filename=user.xls':Content-disposition 是 MIME 協議的擴充套件,MIME 協議指示 MIME 使用者代理如何顯示附加的檔案。Content-Disposition就是當用戶想把請求所得的內容存為一個檔案的時候提供一個預設的檔名。

django版本:Django 1.10 python版本:Python 3.5.1

建立簡單的django框架的網站,進行測試:

前端html檔案:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <div>
10     <p><a href="/output">匯出csv</a></p>
11 </div>
12 </body>
13 </html>

django url:

1 urlpatterns = [
2     url(r'^admin/', admin.site.urls),
3     url(r'^output/', views.output),
4     url(r'^down/', views.down),
5 
6 ]

檢視程式碼:

 1 from django.shortcuts import render,HttpResponse
 2 import xlwt
 3 from io import StringIO,BytesIO
 4 # Create your views here.
 5 # def output(reuqest):
 6 def output(request):
 7     response = HttpResponse(content_type='application/vnd.ms-excel')
 8     response['Content-Disposition'] = 'attachment;filename=user.xls'
 9     wb = xlwt.Workbook(encoding = 'utf-8')
10     sheet = wb.add_sheet(u'人員表單')
11     #1st line
12     sheet.write(0,0, '姓名')
13     sheet.write(0,1, '英文名')
14     sheet.write(0,2, '職位')
15     sheet.write(0,3, '公司電話')
16     sheet.write(0,4, '手機')
17     sheet.write(0,5, 'QQ')
18     sheet.write(0,6, 'MSN')
19     sheet.write(0,7, 'Email')
20     sheet.write(0,8, '辦公地點')
21     sheet.write(0,9, '部門')
22     output = BytesIO()
23     wb.save(output)
24     output.seek(0)
25     response.write(output.getvalue())
26     return response
27 def down(request):
28     return render(request,'download.html')

由於是測試,modle就沒建表,只是簡單做個測試。

需要注意:

1:在HttpResponse中,只有content_type而不是minetype。可以看原始碼。在低版本是minetype,在最新版本django執行會報錯typeerror。

2:在python3中以bytes形式傳輸,所以需要用IO模組中BytesIO而不是StringIO否則報錯。

效果: