def export_selected_data(self,request,queryset):
ops = self.model._meta
workbook = xlwt.Workbook(encoding='utf-8')
dd = datetime.date.today().strftime('%Y%m%d')
file_name = force_text(ops.verbose_name+dd)
sheet = workbook.add_sheet(force_text(ops.verbose_name))
obj_fields = getattr(self,'export_fields',None) or self.list_display or self.fields
head_col_index = 0
for field in obj_fields:
col_name = field
try:
f = ops.get_field(field)
col_name = f.verbose_name
except Exception,e:
f = getattr(self.model,field)
if hasattr(f,'short_description'):
col_name = f.short_description
sheet.write(0,head_col_index,force_text(col_name))
head_col_index+=1
row_index = 1
for obj in queryset:
col_index = 0
for field in obj_fields:
f = field
try:
f = ops.get_field(field)
except Exception,e:
pass
v = getattr(obj,field,'')
if hasattr(v,'__call__') or callable(v):
v = v()
elif type(f) == fields.DateField:
v = v.strftime('%Y-%m-%d')
elif type(f) == fields.DateTimeField:
v = v.strftime('%Y-%m-%d %H:%M')
elif type(f) == fields.CharField and f.choices:
fc = 'get_'+field+'_display'
v = getattr(obj,fc)()
elif type(f) == related.ForeignKey:
v = str(v)
sheet.write(row_index,col_index,v)
col_index += 1
row_index += 1
response = HttpResponse(content_type='application/vnd.ms-excel')
agent = request.META.get('HTTP_USER_AGENT')
nn = smart_str(file_name)
if agent and re.search('MSIE',agent):
nn = urlquote(file_name)
response['Content-Disposition'] = 'attachment; filename=%s.xls'%nn
workbook.save(response)
return response
#self.message_user(request,'SUCCESS')
评论列表
文章目录