【发布时间】:2018-02-10 13:26:18
【问题描述】:
我试图从表单中获取用户输入,然后使用该数据使用 python docx 模块创建文档。但是下载的文件没有在 MS Word 中打开。它说文件已损坏。有人可以帮我弄这个吗?
def resume_form(request):
form = forms.resume()
if request.method == 'POST':
form = forms.resume(request.POST)
if form.is_valid():
document = Document()
document.add_heading(str(form.cleaned_data['full_name']),0)
document.add_heading('Summary', 1)
document.add_paragraph(str(form.cleaned_data['summary']))
f = io.BytesIO()
document.save(f)
length = f.tell()
f.seek(0)
response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename=download.docx'
response['Content-Length'] = length
#document.save(response)
return response
return render(request, 'sample_app/index.html', {'form' : form})
【问题讨论】:
-
您正在损坏此行中的文件 检查此行中的正确扩展名 document 。 response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
-
我从这个网站尝试了 .doc:blogs.msdn.microsoft.com/vsofficedeveloper/2008/05/08/… 它仍然损坏
-
看看这个链接能不能帮到你stackoverflow.com/questions/19400089/…
-
if form.is_valid(): document = Document() document.add_heading(str(form.cleaned_data['full_name']),0) document.add_heading('Summary', 1) document.add_paragraph(str(form.cleaned_data['summary'])) response = HttpResponse(document, content_type='application/vnd.ms-word') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response -
我尝试更改扩展名和其他一些更改。但它仍然无法正常工作。我在记事本中打开文件,它看起来像这样:‰–ÄaLÎ^ÓØ« ƒrálv®ZOâèÞ[1Û¶
标签: python django python-3.x django-views python-requests