首页 > 代码库 > Django 导出CSV

Django 导出CSV

1.在myapp目录下新建文件export.py

   

# coding: utf-8

import sys 

reload(sys) 

sys.setdefaultencoding(‘utf-8‘)

import unicodecsv as csv

import datetime,types

from django.contrib.admin import util as admin_util

from django.utils.translation import ugettext_lazy as _

from django.http import HttpResponse



def export_model_as_csv(modeladmin, request, queryset):

   if hasattr(modeladmin, ‘exportable_fields‘):

       field_list = modeladmin.exportable_fields

   else:

       # Copy modeladmin.list_display to remove action_checkbox

       field_list = modeladmin.list_display[:]

       field_list.remove(‘action_checkbox‘)

   response = HttpResponse(mimetype=‘text/csv‘)

   response[‘Content-Disposition‘] = ‘attachment; filename=%s-%s-export-%s.csv‘ % (

       __package__.lower(),

       queryset.model.__name__.lower(),

       datetime.datetime.now().strftime(‘%Y-%m-%d-%H-%M-%S‘),

   )

   writer = csv.writer(response)

   writer.writerow(

       [admin_util.label_for_field(f, queryset.model, modeladmin).encode(‘gbk‘) for f in field_list],

   )

   for obj in queryset:

       print obj

       csv_line_values = []

       csv_line_tmp = []

       for field in field_list:

           field_obj, attr, value = http://www.mamicode.com/admin_util.lookup_field(field, obj, modeladmin)

           if isinstance(value, unicode) :

               csv_line_values.append(value.encode(‘gbk‘))

           else:

               csv_line_values.append((value.__unicode__()).encode(‘gbk‘))

       writer.writerow(csv_line_values)

   return response

export_model_as_csv.short_description = _(‘Export to CSV‘)

2.修改admin.py

   from cmdb.export import export_model_as_csv #引入类

   

   class ServerAdmin(CustomModelAdmin):

        list_display = ("ip","sys","mark","lastchangedatetime")

        search_fields = ("ip","sys__sysname","mark")

        ordering = ("ip",)

        actions = (export_model_as_csv,)

        exportable_fields =("ip","sys","mark") #需要导出的列


本文出自 “水草” 博客,请务必保留此出处http://961911.blog.51cto.com/951911/1576347

Django 导出CSV