在Django中将openpyxl工作簿对象作为HttpResponse返回。有可能吗?

2024-05-18 06:11:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从django的数据库向访问者提供一个excel格式的数据。

我唯一能想到的方法就是用这些步骤:

  1. 从数据库中提取数据。
  2. openpyxl中的Workbook对象包装它。
  3. 暂时保存在某处。
  4. 再念一遍“rb”。
  5. 使用excel's mime type返回视图。
  6. 删除磁盘上的excel文件。(现在没用了?)

应该可以。但是,我想还有更好的办法。我是说 也许有一种方法可以将openpyxl对象直接返回为HttpResponse 没有中间文件介质。

所以,我的问题是:是否可以返回openpyxlWorbook 反对?(我是新来的openpyxl


Tags: 文件数据对象django方法数据库格式type
2条回答

这对我有效

from openpyxl import Workbook, load_workbook
from openpyxl.writer.excel import save_virtual_workbook

wb = Workbook()
...

response = HttpResponse(content=save_virtual_workbook(wb), content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=Inform.xlsx'
return response

实际上不需要将数据保存在磁盘上的任何位置;openpyxl有一种方法可以做到这一点,尽管它没有很好的文档记录。很久以前,我使用xlwt创建了something like this,但最近我也使用openpyxl在Falcon框架中构建了类似的东西。

把这两个放在一起,你的代码看起来像是:

from django.http import HttpResponse
from openpyxl import Workbook
from openpyxl.writer.excel import save_virtual_workbook


workbook = Workbook()
worksheet = workbook.active

# ... worksheet.append(...) all of your data ...

response = HttpResponse(content=save_virtual_workbook(workbook), mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=myexport.xlsx'
return response

如果您正在生成更大的文件,我建议您考虑使用streamingttpresponse,但我相信这至少会让您继续。

这只是一个基于我工作过的两个项目合并的即兴片段,所以可能不完全正确。不过应该很接近。Falcon的输出看起来像:

response.content_type = 'application/octet-stream;'
response.set_header('Content-Disposition', 'attachment; filename=myexport.xlsx')
response.body = save_virtual_workbook(workbook)

更新: 现在更容易了,因为我使用openpyxl完全重写了我以前的django-excel-response库!现在可以在这里找到:https://github.com/tarkatronic/django-excel-response

您可以使用pip install django-excel-response安装它,并开始使用它作为Django的HttpResponse的替代品!包含的文档很少,欢迎改进/建议。:)

相关问题 更多 >