无法打开通过Django视图作为附件返回的XLS

我使用xlwt来生成一个Excel文件,我在Django视图的HttpResponse中作为附件返回。

from django.http import HttpResponse def my_view(request): ... workbook = xlwt.Workbook(encoding='utf-8') #write my workbook data here workbook.save(#absolute_path_here) response = HttpResponse(mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=worksheet.xls' return response 

该文件被保存到我指定的path,我可以从磁盘正确打开文件,数据存在。 但是,当我尝试从文件下载提示中使用Excel打开文件时,我迎接:

在这里输入图像说明

你试图打开的文件“worksheet.xls”,格式与文件扩展名不同。 打开文件之前,validation该文件是否已损坏并且来自受信任的来源。 你想现在打开文件吗?

而Excel文件没有数据。 我究竟做错了什么?

django HttpResponse是一个类似文件的对象(它提供了write,flush …方法参见文档 )。 因此,您可以直接将其传递给工作簿的保存方法。

 import xlwt wb = xlwt.Workbook() ... ... response = HttpResponse(mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=your-file.xls' wb.save(response) return response 

你需要传递文件的内容到HttpResponse ,否则你发送一个空的响应(没有数据); 这就是为什么你得到这个错误。

 import xlwt wb = xlwt.Workbook() # your code content = StringIO.StringIO() wb.save(content) # "File" is written response = HttpResponse(content.getvalue(), mimetype='application/vnd.ms-excel; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=worksheet.xls' return response 

而且,将字符集与MIMEtypes一起传递总是好的。