通过django视图下载一本xlrd书作为excel文件



我需要下载使用xlrd库在内存中生成的excel文件,认为django视图是直接下载的。我正在尝试以下内容,但我不知道如何将book对象转换为可以包含在HttpResponse

中的内容
from django.http import HttpResponse
from xlrd import Book
def my view:
...
book: Book = <CREATED WITH XLRD>
response = HttpResponse(book, content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="file.xls"'
return response

不测试以下内容。但通常情况下,你会把对象保存到io流中,然后用Django的响应之一来提供它:

import io
from xlrd import Book
from django.http import FileResponse

def my view:
book: Book = <CREATED WITH XLRD>
file = io.BytesIO()
book.save(file)
return FileResponse(file, as_attachment=True, filename="file.xls")

最新更新