脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - django admin后台添加导出excel功能示例代码

django admin后台添加导出excel功能示例代码

2021-06-26 01:18628财经 Python

这篇文章主要介绍了django admin 后台添加导出excel功能示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

django功能强大不单在于他先进的编程理念,很多现有的功能模块更是可以直接拿来使用,比如这个牛掰的admin模块,可以作为一个很好的信息登记管理系统。

admin模块中的actioin是可以自定义添加的,比如这次要介绍的导出excel功能,就可以在action中触发。

本文将详细介绍如何导出admin中录入的数据为excel,可以直接提交给你的leader观看。

首先我们要安装 xlwt 这个工具模块:

?
1
pip install xlwt

import的准备 修改admin.py:

?
1
2
3
4
5
6
7
8
#-*-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:

?
1
2
3
4
5
class testadmin(admin.modeladmin):
  list_display = ('a_name','b_level','...')
  actions = ["export_excel",]
  ...
  export_excel.short_description = "导出excel文件"

添加后的效果如图:

django admin后台添加导出excel功能示例代码

接下来编写导出excel的功能函数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def export_excel(self, request, queryset): #三个参数必不可少,queryset是你要导出的文件名
  for i in queryset:  #这个for循环是为了在多选的时候只导出第一个文件,避免多个被同时导出
    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') #为了能将导出的excel命名为中文,必须转成gb2312
    typess = 'attachment;filename='+filename+'.xls' #这一步命名导出的excel,为登记的case名称
    response['content-disposition'] = typess
    #print typess
  # 创建一个文件对象
  wb = xlwt.workbook(encoding='utf8')
  # 创建一个sheet对象
  sheet = wb.add_sheet('casestudy',cell_overwrite_ok=true) #创建的sheet名称为casestudy,注意如果想要开启覆盖写入,必须将overwrite功能开启

接下来是定义字体和表格样式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 接下里是定义表格的样式,如果你想对不同的表格定义不同的样式只能采用下面这种方式,否则将会默认成一种格式,即使定义了不同的变量,也会影响全局变量
style_heading = xlwt.easyxf("""
      font: # 字体设置
        name microsoft yahei,  # 定义字体为微软雅黑
        colour_index black,  # 字体颜色为黑色
        bold off,  # 不加粗
        height 200; #字体大小 此处的200实际对应的字号是10号
      align: # 对齐方式设置
        wrap off, #自动换行 关闭
        vert center, #上下居中
        horiz center; #左右居中
      pattern: #表格样式设置
        pattern solid,
        fore-colour white; # 表格颜色 白色
      borders: # 表格外框设置
        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, # 此处设置为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') # 设置时间格式样式为 2019-03-01
style_time = style_heading
style_time.num_format_str = 'yyyy-mm-dd hh:mm' # 设置时间格式样式为 2019-03-01 17:30

接下来是合并单元格,这个是一个比较细的工作:

?
1
2
3
4
5
6
7
8
9
10
11
12
    #合并单元格 顺序是从0开始
    sheet.write_merge(0, 0, 1, 3,) # 参数说明为 从第0行到第0行的第1列到第3列合并
    sheet.write_merge(2, 3, 1, 5,) # 参数说明为 从第2行到第3行的第1列到第5列合并
    #多行执行相同的合并可以写个for循环
    for i in range(6,12):
      sheet.write_merge(i,i,1,3,) #相当于在6到12行的第1列到第3列分别合并 如果这个逻辑绕不明白可以自己实践一下
接下来是添加边框,因为合并了单元格不等于自动加边框,导致导出的表格里有未加边框的情况,所以只能先行添加好
 
    #添加边框,可以用两个for来实现,具体逻辑可自行根据实际情况修改
    for i in range(6,12):
      for j in range(1,6):
        sheet.write(i,j,'',style_heading)

接下来是写入表头

?
1
2
3
4
5
6
7
8
# 写入文件标题
sheet.write(0,0,'标题',style_heading)
sheet.write(0,4,'故障等级',style_heading)
sheet.write(1,0,'开始时间',style_heading)
sheet.write(1,2,'结束时间',style_heading)
sheet.write(1,4,'持续时间',style_heading)
sheet.write(2,0,'影响描述',style_heading)
...

接下来是定义表格的宽度和高度

?
1
2
3
4
5
6
7
8
9
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循环批量定义高度或宽度
  sheet.row(i).height_mismatch = true
  sheet.row(i).height = 40*20

接下来是写入数据

?
1
2
3
4
5
6
7
#写入数据
for i in case_study.objects.all().filter(a_name = filenames): # 查询要写入的数据
  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并返回

?
1
2
3
4
5
6
7
8
9
10
11
    # 写出到io
    output = bytesio()
    wb.save(output)
    # 重新定位到开始
    output.seek(0)
    response.write(output.getvalue())
    return response
    
  export_excel.short_description = "导出excel文件"
 
admin.site.register(test,testadmin)

以上就是导出excel的全部代码,由于导出的是xls格式,很多excel新的功能比如瀑布图,雷达图等是没有的,需要各位手动复制表格到 xlsx格式中修改,避免采坑。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.000628.com/node/194

延伸 · 阅读

精彩推荐