使用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 %}
导入

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)

你可能感兴趣的:(使用xadmin后台上传表格)