記錄重寫過程中遇到的問題和最後解決的方法。
需求
重寫django中admin自帶的管理後臺,篩選仿真任務列表,添加一個按鈕,可以將篩選出的仿真任務列表以Excel的形式導出。
用到的第三方庫
# 1.導出Excel的庫
import xlwt
# 2.在內存中讀寫bytes的庫
from io import BytesIO
xlwt庫安裝方式
- 用pip安裝
pip install xlwt
- 源碼安裝(不聯網的機器上)
在 https://pypi.org/project/xlwt/ 中下載 xlwt-1.3.0.tar.gz(我下載時的最新版本)。
上傳壓縮包到機器,解壓,進入目錄,執行命令安裝
python setup.py install
記錄篩選條件
用session記錄用戶點擊的篩選條件,重寫changelist_view方法:
def changelist_view(self, request, extra_context=None):
request.session['excel_params'] = json.dumps(request.GET.dict())
寫導出Excel方法
取參數
# 導出Excel
def export_excel(self, request):
# 取參數
try:
excel_params = json.loads(request.session.get('excel_params'))
except:
excel_params = {}
按篩選條件查詢作業列表後,創建文件對象,準備寫入Excel。
文件操作
# 設置HTTPResponse的類型
response = HttpResponse(content_type='application/vnd.ms-excel')
current_time = datetime.datetime.today().strftime("%Y-%m-%d")
response['Content-Disposition'] = 'attachment;filename=jobs_list.xls' #導出文件名
# 創建一個文件對象
wb = xlwt.Workbook(encoding='utf8')
# 創建一個sheet對象
sheet = wb.add_sheet('order-sheet')
# 設置文件頭的樣式,可以根據自己的需求進行更改
style_heading = xlwt.easyxf("""
font:
name Arial,
colour_index white,
bold on,
height 0xA0;
align:
wrap off,
vert center,
horiz center;
pattern:
pattern solid,
fore-colour 0x19;
borders:
left THIN,
right THIN,
top THIN,
bottom THIN;
""")
# 寫入文件標題(行,列,內容,樣式)
sheet.write(0, 0, '任務名', style_heading)
sheet.write(0, 1, '節點列表', style_heading)
sheet.write(0, 2, 'CPU核數', style_heading)
sheet.write(0, 3, '開始時間', style_heading)
sheet.write(0, 4, '結束時間', style_heading)
sheet.write(0, 5, '運行時間', style_heading)
sheet.write(0, 6, '狀態', style_heading)
sheet.write(0, 7, '核小時數', style_heading)
# 逐行寫Excel.表頭是第0行,內容從第1行寫起
data_row = 1
for job in slurm_jobstatus_list:
# 格式化datetime
sheet.write(data_row, 0, job['JobName'])
sheet.write(data_row, 1, job['NodeList'])
sheet.write(data_row, 2, job['ReqCPUS'])
sheet.write(data_row, 3, job['Start'].replace('T',' '))
sheet.write(data_row, 4, job['End'].replace('T',' '))
sheet.write(data_row, 5, job['Elapsed'])
sheet.write(data_row, 6, job['State'])
sheet.write(data_row, 7, job['job_cpu_time'])
data_row = data_row + 1
# 寫出到IO
output = BytesIO()
wb.save(output)
# 重新定位到開始
output.seek(0)
response.write(output.getvalue())
return response
設置接口url
完成接口後,設置接口url方法:
def get_urls(self):
urls = super(CaeJoblistAdmin, self).get_urls()
my_urls = [
url('export_excel/', self.export_excel)
]
return my_urls + urls
在前段加入按鈕
在change_list.html中加入按鈕
{% extends 'admin/change_list.html' %}
{% load static %}
{% block object-tools-items %}
<div>
<form action="export_excel/" method="POST">
{% csrf_token %}
<button type="submit">導出excel</button>
</form>
</div>
{% endblock %}
完成。
參考文獻: