django admin后臺添加導(dǎo)出excel功能示例代碼
Django功能強大不單在于他先進的編程理念,很多現(xiàn)有的功能模塊更是可以直接拿來使用,比如這個牛掰的admin模塊,可以作為一個很好的信息登記管理系統(tǒng)。
admin模塊中的actioin是可以自定義添加的,比如這次要介紹的導(dǎo)出excel功能,就可以在action中觸發(fā)。
本文將詳細(xì)介紹如何導(dǎo)出admin中錄入的數(shù)據(jù)為excel,可以直接提交給你的leader觀看。
首先我們要安裝 xlwt 這個工具模塊:
pip install xlwt
import的準(zhǔn)備 修改admin.py:
#-*-coding:utf-8 -*- from django.contrib import admin from .models import * from django.http import StreamingHttpResponse from django.shortcuts import render,HttpResponse,redirect import xlwt import os from io import BytesIO
添加action:
class testAdmin(admin.ModelAdmin): list_display = ('a_name','b_level','...') actions = ["export_excel",] ... export_excel.short_description = "導(dǎo)出Excel文件"
添加后的效果如圖:
接下來編寫導(dǎo)出excel的功能函數(shù):
def export_excel(self, request, queryset): #三個參數(shù)必不可少,queryset是你要導(dǎo)出的文件名 for i in queryset: #這個for循環(huán)是為了在多選的時候只導(dǎo)出第一個文件,避免多個被同時導(dǎo)出 filenames = str(i) break; response = HttpResponse(content_type='application/vnd.ms-excel') for i in Case_Study.objects.all().filter(a_name = filenames): filename = i.a_name filename = filename.encode('gb2312') #為了能將導(dǎo)出的excel命名為中文,必須轉(zhuǎn)成gb2312 typess = 'attachment;filename='+filename+'.xls' #這一步命名導(dǎo)出的excel,為登記的case名稱 response['Content-Disposition'] = typess #print typess # 創(chuàng)建一個文件對象 wb = xlwt.Workbook(encoding='utf8') # 創(chuàng)建一個sheet對象 sheet = wb.add_sheet('casestudy',cell_overwrite_ok=True) #創(chuàng)建的sheet名稱為casestudy,注意如果想要開啟覆蓋寫入,必須將overwrite功能開啟
接下來是定義字體和表格樣式:
# 接下里是定義表格的樣式,如果你想對不同的表格定義不同的樣式只能采用下面這種方式,否則將會默認(rèn)成一種格式,即使定義了不同的變量,也會影響全局變量 style_heading = xlwt.easyxf(""" font: # 字體設(shè)置 name Microsoft YaHei, # 定義字體為微軟雅黑 colour_index black, # 字體顏色為黑色 bold off, # 不加粗 height 200; #字體大小 此處的200實際對應(yīng)的字號是10號 align: # 對齊方式設(shè)置 wrap off, #自動換行 關(guān)閉 vert center, #上下居中 horiz center; #左右居中 pattern: #表格樣式設(shè)置 pattern solid, fore-colour white; # 表格顏色 白色 borders: # 表格外框設(shè)置 left THIN, #THIN 為實線 right THIN, top THIN, bottom THIN; """) style_playback = xlwt.easyxf(""" font: name Microsoft YaHei, colour_index black, bold off, height 200; align: wrap 1, # 此處設(shè)置為1時表示開啟自動換行 vert center, horiz left; pattern: pattern solid, fore-colour white; borders: left THIN, right THIN, top THIN, bottom THIN; """) style_time_s = xlwt.easyxf(""" font: name Microsoft YaHei, colour_index black, bold off, height 200; align: wrap off, vert center, horiz center; pattern: pattern solid, fore-colour white; borders: left THIN, right THIN, top THIN, bottom THIN; """,num_format_str='YYYY-MM-DD') # 設(shè)置時間格式樣式為 2019-03-01 style_time = style_heading style_time.num_format_str = 'YYYY-MM-DD hh:mm' # 設(shè)置時間格式樣式為 2019-03-01 17:30
接下來是合并單元格,這個是一個比較細(xì)的工作:
#合并單元格 順序是從0開始 sheet.write_merge(0, 0, 1, 3,) # 參數(shù)說明為 從第0行到第0行的第1列到第3列合并 sheet.write_merge(2, 3, 1, 5,) # 參數(shù)說明為 從第2行到第3行的第1列到第5列合并 #多行執(zhí)行相同的合并可以寫個for循環(huán) for i in range(6,12): sheet.write_merge(i,i,1,3,) #相當(dāng)于在6到12行的第1列到第3列分別合并 如果這個邏輯繞不明白可以自己實踐一下 接下來是添加邊框,因為合并了單元格不等于自動加邊框,導(dǎo)致導(dǎo)出的表格里有未加邊框的情況,所以只能先行添加好 #添加邊框,可以用兩個for來實現(xiàn),具體邏輯可自行根據(jù)實際情況修改 for i in range(6,12): for j in range(1,6): sheet.write(i,j,'',style_heading)
接下來是寫入表頭
# 寫入文件標(biāo)題 sheet.write(0,0,'標(biāo)題',style_heading) sheet.write(0,4,'故障等級',style_heading) sheet.write(1,0,'開始時間',style_heading) sheet.write(1,2,'結(jié)束時間',style_heading) sheet.write(1,4,'持續(xù)時間',style_heading) sheet.write(2,0,'影響描述',style_heading) ...
接下來是定義表格的寬度和高度
sheet.col(0).width = 3333 sheet.col(1).width = 6666 ... sheet.row(0).height_mismatch = True # 高度可不依賴字體大小定義,定義高度時最好開啟此選項 sheet.row(0).height = 40*20 ... for i in range(7,12): # 也可以通過for循環(huán)批量定義高度或?qū)挾? sheet.row(i).height_mismatch = True sheet.row(i).height = 40*20
接下來是寫入數(shù)據(jù)
#寫入數(shù)據(jù) for i in Case_Study.objects.all().filter(a_name = filenames): # 查詢要寫入的數(shù)據(jù) sheet.write(0,1,i.a_name,style_playback) sheet.write(0,5,i.b_level,style_heading) sheet.write(1,1,i.d_starttime,style_time) sheet.write(1,3,i.e_endttime,style_time) ...
最后是寫出道IO并返回
# 寫出到IO output = BytesIO() wb.save(output) # 重新定位到開始 output.seek(0) response.write(output.getvalue()) return response export_excel.short_description = "導(dǎo)出Excel文件" admin.site.register(test,testAdmin)
以上就是導(dǎo)出excel的全部代碼,由于導(dǎo)出的是xls格式,很多excel新的功能比如瀑布圖,雷達圖等是沒有的,需要各位手動復(fù)制表格到 xlsx格式中修改,避免采坑。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python paramiko連接ssh實現(xiàn)命令
這篇文章主要為大家介紹了python paramiko連接ssh實現(xiàn)的命令詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07python 中的list和array的不同之處及轉(zhuǎn)換問題
python中的list是python的內(nèi)置數(shù)據(jù)類型,list中的數(shù)據(jù)類不必相同的,而array的中的類型必須全部相同。這篇文章給大家介紹了python 中的list和array的不同之處及轉(zhuǎn)換問題,需要的朋友參考下吧2018-03-03Windows下PyCharm配置Anaconda環(huán)境(超詳細(xì)教程)
這篇文章主要介紹了Windows下PyCharm配置Anaconda環(huán)境,本文給大家分享一篇超詳細(xì)教程,通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07