如何在django中以views.py的excel选项创build下载

我想添加我的Django应用程序的views.py选项“下载为Excel”。 HttpResponse在html文件中。 这几个views.py看起来像这样

def auto_run_html(request): htmlfile = HttpResponse() Month_no = request.GET['Month'] htmlfile.write('<html><HEAD><LINK href="/static/timesheet.css" rel="stylesheet" type="text/css"></HEAD>') htmlfile.write('<body>') htmlfile.write('''<table class = "Emp_Details" > <tr style="text-align:left"> <th>{}</th><th>{}</th> </tr> <tr style="text-align:left"> <th>{}</th><th>{}</th> </tr> <tr style="text-align:left"> <th>{}</th><th>{}</th> </tr> </table>'''.format('Department',dept_row,'Employee ID',dept_row[2],'Employee Name',dept_row)) return HttpResponse(htmlfile) 

在这里我想添加下载作为excel操作。 我试过这个输出csv,但它只是为了显示为csv文件,而不是浏览器中的html。告诉用户可以保存为csv文件的文档,但它只能提供html页面的选项。

我正在使用django 1.6&python 2.7。 这可能是重复的。

我是新来的python,如果它只能由python-excel程序完成,那么请举例参考我的上述代码。 预先感谢。

这是我的csv编码veiws.py.Please标记我在哪里做错了。

 def auto_run_html(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' htmlfile = csv.writer(response) htmlfile.writerow('''<table class = "Emp_Details" > <tr style="text-align:left"> <th>{}</th><th>{}</th> </tr> <tr style="text-align:left"> <th>{}</th><th>{}</th> </tr> <tr style="text-align:left"> <th>{}</th><th>{}</th> </tr> </table>'''.format('Department',dept_row,'Employee ID',dept_row[2],'Employee Name',dept_row)) return response 

CSV是要走的路。 您只需要正确指定内容types和处置。 例如:

 response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="document.csv"' 

然后使用标准的python csv模块形成实际的CSV。