16.6. Serving Word on the Web

Older versions of Word acted much like Internet Explorer plug-ins in that they opened files within the browser frame. Newer versions tend to keep to themselves — opening a link to a .doc file in a separate Office application.

Consider this use of the ASP.NET HyperLink control to point to a Word document:

<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="~/clientquotes.doc">Client Comments in Word
</asp:HyperLink>

At runtime, when the user clicks the link, Internet Explorer launches the Open or Save dialog box. When the user selects Open, Word fires up and displays the document in read-only mode.

To serve a Word and Excel file programmatically, follow these steps.

  1. Add a Microsoft Word document to your project.

    The file clientquotes.doc is used in this example.

  2. Add ASP.NET Web form named office.aspx to your project.

  3. From the Toolbox, add an ASP.NET Button control named btnServeWord to the page.

  4. Double-click the button to create a handler for the Click event and insert this code:

Try
  Response.Buffer = True
  Response.Clear()
  Response.ClearContent()
  Response.ClearHeaders()
  Response.ContentType = "application/msword"
Response.AddHeader("Content-Disposition", _
        "attachment;filename=clientquotes.doc")
  Response.WriteFile(Server.MapPath _
          ("~/clientquotes.doc"))
  Response.End()
Catch exc As Exception
  Response.Write(exc.Message)
End Try

NOTE

Depending on where you look, the standard MIME type for Microsoft Word may be given as application/ms-word or application/word ...

Get ASP.NET 3.5 For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.