gpt4 book ai didi

python - Django:如何通过 Django View 下载 .xls 文件

转载 作者:行者123 更新时间:2023-12-04 08:25:23 26 4
gpt4 key购买 nike

我有一个按钮可以下载扩展名为 .xls 的 excel 文件。我正在使用模块 xlrd 来解析文件并将其返回给用户。但是,它似乎将对象名称而不是数据添加到 excel 文件中。

如何将包含数据而不是对象名称的文件返回给用户?

查看

def download_file(self, testname):
import csv, socket, os, xlrd
extension = '.xls'
path = r"C:\tests\{}_Report{}".format(testname, extension)
try:
f = xlrd.open_workbook(path)
response = HttpResponse(f, content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension)
return response
except Exception as Error:
return HttpResponse(Error)
return redirect('emissions_dashboard:overview_view_record')

Excel 结果

下载成功:

enter image description here

内容:

enter image description here

注意:我知道这是一种旧文件格式,但对于这个特定项目是必需的。

最佳答案

您正在尝试发送 xlrd.book.Book 对象,而不是文件。

您使用 xlrd 在工作簿中执行操作,然后保存到文件中。

workbook = xlrd.open_workbook(path)
#... do something
workbook.save(path)

现在您可以像发送任何其他文件一样发送它:

with open(path, 'rb') as f:
response = HttpResponse(f.read(), content_type="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension)

关于python - Django:如何通过 Django View 下载 .xls 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65288120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com