简体   繁体   English

Django用于生成生成的excel文件

[英]Django to serve generated excel file

I looked at the various questions similar to mine, but I could not find anything a fix for my problem. 我查看了与我类似的各种问题,但我找不到任何解决问题的方法。

In my code, I want to serve a freshly generated excel file residing in my app directory in a folder named files 在我的代码中,我想在一个名为files的文件夹中提供一个新生成的excel文件,该文件位于我的app目录中

excelFile = ExcelCreator.ExcelCreator("test")
excelFile.create()
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'
return response

So when I click on the button that run this part of the code, it sends to the user an empty file. 因此,当我单击运行此部分代码的按钮时,它会向用户发送一个空文件。 By looking at my code, I can understand that behavior because I don't point to that file within my response... 通过查看我的代码,我可以理解这种行为,因为我没有在我的回复中指向该文件...

I saw some people use the file wrapper (which I don't quite understand the use). 我看到有些人使用文件包装器(我不太了解它的使用)。 So I did like that: 所以我喜欢这样:

response = HttpResponse(FileWrapper(excelFile.file),content_type='application/vnd.ms-excel')

But then, I receive the error message from server : A server error occurred. 但是,我从服务器收到错误消息:发生服务器错误。 Please contact the administrator. 请联系管理员。

Thanks for helping me in my Django quest, I'm getting better with all of your precious advices! 感谢您帮助我完成我的Django任务,我的所有宝贵建议都让您变得更好!

First, you need to understand how this works, you are getting an empty file because that is what you are doing, actually: 首先,你需要了解它是如何工作的,你得到一个空文件,因为这就是你正在做的事情,实际上:

response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'

HttpResponse receives as first arg the content of the response, take a look to its contructor: HttpResponse首先收到响应内容的arg,看看它的构造函数:

def __init__(self, content='', mimetype=None, status=None, content_type=None):

so you need to create the response with the content that you wish, is this case, with the content of your .xls file. 因此,您需要使用您希望的内容创建响应,在这种情况下,使用.xls文件的内容。

You can use any method to do that, just be sure the content is there. 您可以使用任何方法来做到这一点,只需确保内容存在。

Here a sample: 这是一个样本:

import StringIO
output = StringIO.StringIO()
# read your content and put it in output var
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content, mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'

I would recommend you use: 我建议你使用:

python manage.py runserver

to run your application from the command line. 从命令行运行您的应用程序。 From here you will see the console output of your application and any exceptions that are thrown as it runs. 从这里,您将看到应用程序的控制台输出以及运行时抛出的任何异常。 This may provide a quick resolution to your problem. 这可以快速解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM