使用xadmin后台上传表格

1,新增excel.py文件

路径:xadmin/plugins/excel.py 内容如下:
# -*- coding: utf-8 -*-
import xadmin
from xadmin.views import BaseAdminPlugin, ListAdminView
from django.template import loader


#excel 导入
class ListImportExcelPlugin(BaseAdminPlugin):
    import_excel = False
    # 入口函数, 通过此属性来指定此字段是否加载此字段
    def init_request(self, *args, **kwargs):
        return bool(self.import_excel)
    # 如果加载, 则执行此函数添加一个 导入 字段
    def block_top_toolbar(self, context, nodes):
        nodes.append(loader.render_to_string('xadmin/excel/model_list.top_toolbar.import.html'))
xadmin.site.register_plugin(ListImportExcelPlugin, ListAdminView)

2,新增model_list.op_toolbar.import.html文件

路径:xadmin/templates/xadmin/excle/model_list.op_toolbar.import.html

内容如下:

{% load i18n %}
<div class="btn-group export">
    <a class="dropdown-toggle btn btn-default btn-sm" data-toggle="dropdown" href="#"><i class="icon-share"></i> 导入 <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
        <li><a data-toggle="modal" data-target="#export-modal-import-excel"><i class="icon-circle-arrow-down"></i> 导入 Excel</a></li>
   </ul>
    <script>
        function fileChange(target){
 //检测上传文件的类型
             var imgName = document.all.submit_upload.value;
             var ext,idx;
             if (imgName == ''){
                 document.all.submit_upload_b.disabled=true;
                 alert("请选择需要上传的 xls 文件!");
                 return;
             } else {
                 idx = imgName.lastIndexOf(".");
                 if (idx != -1){
                     ext = imgName.substr(idx+1).toUpperCase();
                     ext = ext.toLowerCase( );
 {#                    alert("ext="+ext);#}
                     if (ext != 'xls' && ext != 'xlsx'){
                         document.all.submit_upload_b.disabled=true;
                         alert("只能上传 .xls 类型的文件!");

                         return;
                     }
                 } else {
                     document.all.submit_upload_b.disabled=true;
                     alert("只能上传 .xls 类型的文件!");
                     return;
                 }
             }

         }
     </script>
     <div id="export-modal-import-excel" class="modal fade">
       <div class="modal-dialog">
         <div class="modal-content">
           <form method="post" action="" enctype="multipart/form-data">
               {% csrf_token %}
           <div class="modal-header">
             <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
             <h4 class="modal-title">导入Excel</h4>
           </div>
           <div class="modal-body">
                <input type="file" onchange="fileChange(this)" name="excel" id="submit_upload">

           </div>
           <div class="modal-footer">
             <button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
             <button class="btn btn-success" type="submit" id="submit_upload_b"><i class="icon-share"></i> 导入</button>
          </div>
           </form>
        </div><!-- /.modal-content -->
       </div><!-- /.modal-dalog -->
     </div><!-- /.modal -->

</div>

3,重写adminx.py的post函数,用于接收上传表格的请求,最后注册xadmin中。其中上传表格的处理逻辑在这里些,这里简单的引入了APP的model。

from django.http import HttpResponseRedirect
from xlrd import open_workbook
import xadmin
from channel.models import Channel

class XadminChannel(object):
    #import_excle = True在后台页面显示上传按钮
    import_excel = True
    list_display = ['name',]

    # 每页显示多少个
    list_per_page = 20
    # 配置在哪些字段搜索
    search_fields = ['name']
    # 配置过滤字段
    list_filter = ['name']
    # 导出字段
    list_export_fields = ('name',)

    def post(self, request, *args, **kwargs):
        if 'excel' in request.FILES:
            execl_file = request.FILES.get('excel')
            wb = open_workbook(filename=None, file_contents=request.FILES['excel'].read())
            table = wb.sheets()[0]
            # sheet1 = wb.sheet_by_index(0)
            rows = table.nrows  #获取行数
            cols = table.ncols  #获取列数
            for r in range(1,rows):
                name = table.cell(r,0).value
                bianmaqi = table.cell(r,1).value
                jieru = table.cell(r, 2).value
                type = table.cell(r, 3).value
                pindao_id = table.cell(r, 4).value
                beizhu = table.cell(r, 5).value
                try:
                    a = Channel.objects.filter(name=name)
                    if a:
                        continue
                    elif name == None or name == '':
                        continue
                    else:
                        channel = Channel()
                        channel.name = name
                        channel.save()
                except:
                    pass
            return HttpResponseRedirect('http://127.0.0.1:8000/channel/channel/')
        return super(XadminChannel, self).post(request, args, kwargs)
#APP注册
xadmin.site.register(Channel, XadminChannel)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容