Django输出word文件(.doc),仅在内容中显示原始html [英] Django output word files(.doc),only show raw html in the contents
问题描述
我正在使用Django 1.4编写一个Web应用程序,我希望我的一个视图使用以下代码输出mirosoft word文档:
I am writing a web app using Django 1.4.I want one of my view to output mirosoft word docs using the follwoing codes:
response = HttpResponse(view_data, content_type='application/vnd.ms-word')
response['Content-Disposition'] = 'attachment; filename=file.doc'
return response
然后,我可以下载file.doc成功,但是当我打开.doc文件时,我只能找到这样的原始html
Then ,I can download the file.doc successfully ,but when I open the .doc file ,I only find the raw html like this
<h1>some contents</h1>
不是标题1标题。
I是python&的新手Django,我知道这可能是html转义的问题,有人可以帮我吗?
谢谢!:)
I am new to python & Django ,I know this maybe some problems with html escape,can some one please help me with this ? Thank you !:)
推荐答案
除非您有某种将响应(这里是HTML)转换为.doc文件,您将获得的是一个文本文件,其中包含带有扩展名.doc的回复。如果您愿意使用.docx文件,则有一个很棒的python库,名为 python-docx 应该可以使用lxml库生成格式正确的docx文件。
Unless you have some method of converting your response (here HTML I assume) to a .doc file, all you will get is a text file containing your response with the extension .doc. If you are willing to go for .docx files there is a wonderful python library called python-docx you should look in to that allows you to generate well formed docx files using the lxml library.
或者,使用如下模板:
<html>
<head>
<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html; charset=UTF-8"">
<meta name=ProgId content=Word.Document>
<meta name=Generator content=""Microsoft Word 9"">
<meta name=Originator content=""Microsoft Word 9"">
<style>
@page Section1 {size:595.45pt 841.7pt; margin:1.0in 1.25in 1.0in 1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}
div.Section1 {page:Section1;}
@page Section2 {size:841.7pt 595.45pt;mso-page-orientation:landscape;margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}
div.Section2 {page:Section2;}
</style>
</head>
<body>
<div class=Section2>
'Section1: Portrait, Section2: Landscape
[your text here]
</div>
</body>
</html>
这应该根据此asp.net论坛帖子以MIME类型 application / msword
返回时,请创建有效的.doc文件。使用 UTF-8
字符集(因此请确保所有字符串都是unicode)。
This should, according to this asp.net forum post make a valid .doc file when returned as mime type application/msword
using UTF-8
charset (so make sure strings are all unicode).
这篇关于Django输出word文件(.doc),仅在内容中显示原始html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!