0

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

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>

not a heading1 title.

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 !:)

NextStep
  • 1,035
  • 3
  • 14
  • 18

1 Answers1

2

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.

Alternatively, use a template such as:

<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>

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).

Drakekin
  • 1,341
  • 1
  • 11
  • 23
  • I could output the .doc files like this without any problems with the asp.net technique,I could even put any css rules in the .doc file.I thought those stuff are the same in Danjo & Python world .... – NextStep May 04 '12 at 07:50
  • yes,it works! thank you so much ,Drakekin!~~People said you always get a solution in stackoverflow,that's definitely true!~~~ – NextStep May 04 '12 at 08:07