class AdminReport(admin.ModelAdmin): actions = ["saveexecl"] # 自定義的action(導出到excel表格) list_display = ("id",'offer','day_time', 'idfa', 'submit_result_text', 'callback_result_text') # 顯示的列 search_fields = ('day_time','callback_result_text') # 能夠搜索的字段 date_hierarchy = 'day_time' # 按照日期顯示 list_filter = ('offer',) # 過濾條件 list_per_page = 500 # 每頁顯示500條,太多了可能會出現服務器崩掉的狀況 def saveexecl(self,request,queryset): Begin = xlwt.Workbook() sheet = Begin.add_sheet("response") cols = 0 for query in queryset: # you need write colms # 好像有個方法能夠一次性寫入全部列,記不清了,只能用這種簡單的方法去實現 sheet.write(cols,1,str(query.idfa)) # 寫入第一列 sheet.write(cols,2,str(query.day_time)) # 寫入第二列 sheet.write(cols,3,str(query.keyword)) # 寫入第三列 cols += 1 Begin.save("%s" %(filename)) def file_iterator(filename,chuck_size=512): with open(filename,"rb") as f: while True: c = f.read(chuck_size) if c: yield c else: break response = StreamingHttpResponse(file_iterator(filename)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{}"'.format("result.xls") return response saveexecl.short_description = "導出Excel" # 按鈕顯示名字 admin.site.register(Report, AdminReport) # 註冊到admin