这是我下载 zip 文件的代码,其中包含 .docx 文件,
def reportsdlserien(request):
selected_sem = request.POST.get("semester","SS 2016")
docx_title="Report_in_%s.docx" % selected_sem.replace(' ','_')
document = Document()
f = io.BytesIO()
zip_title="Archive_in_%s.zip" % selected_sem.replace(' ','_')
zip_arch = ZipFile( f, 'a' )
document.add_heading("Report in "+selected_sem, 0)
document.add_paragraph(date.today().strftime('%d %B %Y'))
document.save(docx_title)
zip_arch.write(docx_title)
zip_arch.close()
response = HttpResponse(
f.getvalue(),
content_type='application/zip'
)
response['Content-Disposition'] = 'attachment; filename=' + zip_title
return response
唯一的问题是,它还会创建我不需要的 .docx 文件。我也想将 BytesIO 用于 docx 文件,但无法将其添加到存档中,命令 zip_arch.write(BytesIOdocxfile)
不起作用。还有另一个命令可以做到这一点吗?
谢谢!
最佳答案
使用writestr()
向存档添加一些字节的函数:
data = StringIO()
document.save(data) # Or however the library requires you to do this.
zip_arch.writestr(docx_title, bytes(data.getvalue()))
我只使用 StringIO 完成了此操作,但我不明白为什么 BytesIO 不能同样工作。
关于python - 如何将临时 .docx 文件添加到 django 中的 zip 存档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26559238/