Write Office Documents with ASP
ASP has the ability to dynamically output virtually any type of file,
provided that the correct file format is being used. The easiest type to write
would obviously be text, which is what we are already doing when we output
webpages. The other type, binary, is harder to do since ASP doesn’t natively
support binary variables. Today we will be using standard text output and the
appropriate MIME file type to turn out a dynamic Microsoft Word document and a
Microsoft Excel document.
ContentType
The first thing we need to do is set the appropriate file type so that the
browser knows what to do with the file. We do this using the ContentType setting
of the Response object. For Word, the content type is application/msword. For
Excel, its application/vnd.ms-excel. So we would use the either of the lines
of code below for Word or Excel documents, respectively. This line must come before ANY
data is output.
Response.ContentType = "application/msword" |
Response.ContentType = "application/vnd.ms-excel" |
If the user is using Internet Explorer, the file will most likely be sent to
an Office plugin that will show it within the browser window. For different
reasons, this can sometimes be annoying for both the user and the programmer. If
you do not want your file to be displayed in the user’s browser window, and
instead want to force the save dialog box to pop up, use the line below right
before/after setting the ContentType.
Response.AddHeader "Content-Disposition", "attachment;filename=NAME.doc" |
Writing the File
Since Word and Excel will take text input, we will be outputting our data in the
same way we do with HTML. Actually, the format we will be using is HTML! Even
color formatting, CSS, and meta tags are supported.
For Word, you can just write HTML as you normally would, except you are gearing
it towards Word viewing. HTML tables, CSS, and meta tags are all supported. You
can use the meta tags to set the document properties that Word has, such as Title
and Author. Being in Word, you probably would want to stay away from images
unless you know the user will always be connected to the internet to actually see them.
| Sample Word Document |
<% |
The same applies for Excel as does for Word except you are writing an HTML
table to make your sheet. You can even use Excels functions by outputting the
function as the table cell value.
| Sample Excel Document |
<% |
As you can see, with the simplicity of writing Word/Excel documents, you can
easily implement them into your site where needed. Other possible uses
include expense sheets retrieved from a database and formatted in
Excel, or printable forms in Word with dynamic user information.
Posted in: Archive
