ASP: export data to a Ms Word document

We can create a Ms Word document as output of an ASP page. In the past I published articles about exporting to Ms Excel, to Ms Access and to PDF. In this post we'll see how to export data to Ms Word.

The way data is exported to a Ms Word file is probably the easiest. I assume we gather data from a database and have a resulting recordset (called RS_Word). We can display the records with a repeat region or not. In the following example I assume the data is unique, thus we will not use a repeat region. Let's imagine the data is just some pieces of plain text.


The code
There's not much to say about the code. Anyway, the first thing we do is to create a variable for the file name:
<%
Dim file
file = "filename.doc"
Change filename with an appropriate file name. We then start creating the Word file:
With Response
    .Buffer = True
    .ContentType = "application/msword"
    .AddHeader "content-disposition", "inline; filename=" & file
Now we insert the content of the Word document. It is very easy to do and a single line is enough to create - as in the example - a title:
    .Write "
" & RS_Word.Fields.Item("title").Value & "


"
Then we insert a new line:

    .Write strLine
And continue inserting the text:
    .Write "

" & RS_Word.Fields.Item("text").Value
Finally we wrap everything up:
    .Flush
    .End
End With
%>
Very straightforward, isn't it?

As usual, let me know what you think in the comment section below.