使用django和HttpResponse导出用于用户下载的xls文件时出现问题

时间:2011-07-12 20:45:33

标签: django httpresponse xlwt

我目前正在使用xlwt创建一个电子表格,并尝试将其导出为django中的HttpResponse供用户下载。我的代码如下所示:

response = HttpResponse(mimetype = "application/vnd.ms-excel")
response['Content-Disposition'] = 'attachment; filename = %s +".xls"' % u'Zinnia_Entries'
work_book.save(response)
return response

这似乎是正确的方法,但我得到了:

Traceback (most recent call last):
  File "C:\dev\workspace-warranty\imcom\imcom\wsgiserver.py", line 1233, in communicate
    req.respond()
  File "C:\dev\workspace-warranty\imcom\imcom\wsgiserver.py", line 745, in respond
    self.server.gateway(self).respond()
  File "C:\dev\workspace-warranty\imcom\imcom\wsgiserver.py", line 1927, in respond
    response = self.req.server.wsgi_app(self.env, self.start_response)
  File "C:\dev\workspace-warranty\3rdparty\django\core\servers\basehttp.py", line 674, in __call__
    return self.application(environ, start_response)
  File "C:\dev\workspace-warranty\3rdparty\django\core\handlers\wsgi.py", line 252, in __call__
    response = middleware_method(request, response)
  File "C:\dev\workspace-warranty\imcom\imcom\seo_mod\middleware.py", line 33, in process_response
    response.content = strip_spaces_between_tags(response.content.strip())
  File "C:\dev\workspace-warranty\3rdparty\django\utils\functional.py", line 259, in wrapper
    return func(*args, **kwargs)
  File "C:\dev\workspace-warranty\3rdparty\django\utils\html.py", line 89, in strip_spaces_between_tags
    return re.sub(r'>\s+<', '><', force_unicode(value))
  File "C:\dev\workspace-warranty\3rdparty\django\utils\encoding.py", line 88, in force_unicode
    raise DjangoUnicodeDecodeError(s, *e.args)
DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xd0 in position 0: invalid continuation byte. You passed in 

(我离开了剩下的部分因为我得到了很长的一行\ xd0 \ xcf \ x11 \ xe0 \ xa1 \ xb1 \ x1a \ xe1 \ x00这种东西)

你们对这件事可能有什么不妥吗?是因为我的一些写入值看起来像这样:

work_sheet.write(r,#,information)其中信息未转换为unicode?

2 个答案:

答案 0 :(得分:0)

response['Content-Disposition'] = 'attachment; filename = %s +".xls"' % u'Zinnia_Entries'

应该只是

response['Content-Disposition'] = 'attachment; filename = %s.xls' % u'Zinnia_Entries'

没有引号.xls,否则输出将是

u'attachment; filename = Zinnia_Entries +".xls"'

所以尝试改变它。

但是也看看这个答案。它有一个非常有用的小功能输出xls文件。

django excel xlwt

答案 1 :(得分:0)

解决了这个问题。显然有人把一些时髦的中间件放在那里,分别是黑客攻击,追加和添加等等。等。到文件。什么时候不应该。

无论如何,随着它消失了文件出口完美。

@Storm - 谢谢你的帮助!