我有几个问题,无法弄清楚,也许有联系。
问题 1.1:文件在 django 文档中导出并且它可以工作,但是当我尝试重命名它时,它有一些错误。我要这样with pd.ExcelWriter(newdoc + 'output.xlsx') as writer:
为了每个文件都有一个"new"名称。
我收到这个错误,TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str'
问题 1.2:如何添加路径保存?
问题2:我可以下载文件,但它是空的,文件名为 Donwload.xlsx。我想成为这样,但这有很多错误......
filename = newdoc + '_calculated.xlsx'
response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
当我这样做时,我得到了这个......在终端 UserWarning: Calling close()
在已经关闭的文件上。这在浏览器中TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str'
这是views.py,如果代码是这样,没有错误,但我必须下载空文档。def my_view(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
with pd.ExcelWriter('output.xlsx') as writer: #problem 1
for name, df in dfs.items():
#pandas code for uploaded excel file
out.to_excel(writer, sheet_name=name)
output.seek(0)
response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' #problem 2
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})
最佳答案
output = io.BytesIO()
你在这里创建的根本没有使用。
尝试改变 with pd.ExcelWriter('output.xlsx') as writer:
到writer = pd.ExcelWriter(output)
否则 BytesIO 可能会被 ExcelWriter 关闭,然后 Django 会尝试再次关闭它。给你双重关闭错误。
您的问题 2 似乎是类型错误。
filename = newdoc + '_calculated.xlsx'
您的 newdoc 不是字符串,而是“InMemoryUploadedFile”,您可能需要通过执行以下操作来访问其名称filename = f"{newdoc.name}_calculated.xlsx"
关于python - 在django中下载和保存文档的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69013296/