Accessing Word in ASP.Net

52675 Users read it.
by R.Arockia Jayaseelan (June 23, 2005)

Accessing Word in ASP.Net

       This article explains how to access or generate the word report using ASP.Net
User Rating (19 votes)
11 reviews available | Read the reviews »
Author(s):R. Arockia Jayaseelan
User Level:Intermediate
Language:VB.NET
Platform:Windows
Product(s):VS.NET, .NET Web Matrix

Accessing Word in ASP.Net

Recently, I faced a new requirement in ASP.Net. The requirement like there is a pre formatted Word template; I have to fetch the information from data base and to be replacing some values in pre formatted template and this to be saved as word document. The generated reports are to be sent to their customer by our client.

This is like generating word report, how to accomplish this. Here I am using find and replace concept to meet the requirement. Just go through the code you can easily understand it.

First create you ASP.Net web application, add one class file called “WordApp.vb” and paste the following code

 

WordApp.vb

 

Imports System

Imports System.ComponentModel

Public Class WordAppl

    Private oWordAppl As Word.ApplicationClass

    Private oDoc As Word.Document

    Public Sub New()

        oWordAppl = New Word.ApplicationClass

    End Sub

    ' Open a file (the file must exists) and activate it

    Public Sub Open(ByVal strFileName As String)

        Dim fileName As Object = strFileName

        Dim readOnly1 As Object = False

        Dim isVisible As Object = True

        Dim missing As Object = System.Reflection.Missing.Value

        oDoc = oWordAppl.Documents.Open(fileName, missing, readOnly1, missing, missing, missing, missing, missing, missing, missing, missing, isVisible)

        oDoc.Activate()

    End Sub

    Public Sub Open()

        Dim missing As Object = System.Reflection.Missing.Value

        oDoc = oWordAppl.Documents.Add(missing, missing, missing, missing)

        oDoc.Activate()

    End Sub

    Public Sub Quit()

        Dim missing As Object = System.Reflection.Missing.Value

        oWordAppl.Application.Quit(missing, missing, missing)

    End Sub

    Public Sub Save()

        oDoc.Save()

    End Sub

    Public Sub SaveAs(ByVal strFileName As String)

        Dim missing As Object = System.Reflection.Missing.Value

        Dim fileName As Object = strFileName

        oDoc.SaveAs(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)

    End Sub

    Public Sub FindAndReplacement(ByVal strFind As String, ByVal strReplace As String)

        Try

            oWordAppl.Selection.HomeKey(Word.WdUnits.wdStory, Word.WdMovementType.wdExtend)

            With oWordAppl.Selection.Find

                .Text = strFind

                With .Replacement

                    .Text = strReplace

                End With

                .Execute(Replace:=Word.WdReplace.wdReplaceAll)

            End With

        Catch ex As Exception

            'ClientUtilities.ShowErrorMessage(ex)

        End Try

    End Sub

End Class

 

When you compile the above code, you may get an error. To overcome this error, do add Microsoft Word 10.0 Object Library (available under COM tab) as reference.

Next you have to specify the template path, document storing location. Better you can maintain this information in your web config file. The web config contains the following keys for Template path and Document path. Just add the following keys in web config file.

 

web.config

 

<configuration>

  <appSettings>

      <add key="WordMod" value="C:\\WordApplication\\template\\" />    

      <add key="WordDoc" value="C:\WordApplication\document\" /> 

  </appSettings>

  <system.web>

      ...

  <system.web>

<configuration>

 

Put your template file based on configuration information. Next create web form and add one button control in it and add the following code under button click event.

 

          Form1.vb

 

Imports System

Imports System.ComponentModel

Imports System.Configuration

Imports System.Collections

Public Class Nominate

    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Protected WithEvents Button1 As System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by the Web Form Designer.

    'Do not delete or move it.

    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init

        'CODEGEN: This method call is required by the Web Form Designer

        'Do not modify it using the code editor.

        InitializeComponent()

    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

     

      

    End Sub

  

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Put user code to initialize the page here

        Dim test As New WordAppl

        Dim TemplatePath As String = ConfigurationSettings.AppSettings("WordMod")

        Dim DocumentPath As String = ConfigurationSettings.AppSettings("WordDoc")

        test.Open(TemplatePath & "Test.dot")

        test.FindAndReplacement("<<company>>", "JAYASEELAN")

        test.SaveAs(DocumentPath & "Test.doc")

        test.Quit()

    End Sub

End Class

 

When you click button in your web page, it creates new document available in your document folder as per you config information

 

R.Arockia Jayaseelan

R.Arockia Jayaseelan* Having 6+ Years of experience in Client Server and Web related Technologies.

* Working as a Software Engineer, USA.

See All Postings From R.Arockia Jayaseelan >>

User Reviews

Total of 11 reviews
tips
Written by Vijay Balaji on May 23, 2007

When ever u invoke a com object from web app, if the impersnate is off then it will try to run in iis security context. so u will get this 'access denied exception'. giving rights to entire directory would be security vulenerable. Couple of ...

RE: Access Denied Error and Microsoft word 11.0 object library
Written by brambi brambi on May 3, 2007

Add Imports Microsoft.Office.Interop.Word in wordapp.vb replace 'word.' occurrences with 'Microsoft.Office.Interop.Word.' in wordapp.vb. I have done it and it works Unfortunately when I open the dot file (' oDoc = ...

error while object creation
Written by Shine SR on December 26, 2006

hi, I referred the library Microsoft word 11.0 object library. But while I try to create the object of Word.ApplicationClass, it shows error that Type word.ApplicationClass is not defined. Pls give me instructions to correct it ASAP. Regards, Shine ...

RE: Access Denied Error
Written by R.Arockia Jayaseelan on September 18, 2006

Please do verify your IIS authenitication for ASP.NET users. If you are not having access permission you may encounter this problem.

Access Denied Error
Written by Mohana Sub on September 8, 2006

Good Article!! When i tried to run the code, get the same error like Alex got. Access denied. Source Error: Line 3: Private oDoc As Word.Document Line 4: Public Sub New() Line 5: oWordAppl = New Word.ApplicationClass Line ...

RE: System.NullReferenceException: Object reference not set to an instance of an object
Written by R.Arockia Jayaseelan on May 31, 2006

When you compile the above code, you may get an error. To overcome this error, do add Microsoft Word 10.0 Object Library (available under COM tab) as reference.

System.NullReferenceException: Object reference not set to an instance of an object
Written by Senthil V on May 31, 2006

Hi,I tried this code but 'System.NullReferenceException: Object reference not set to an instance of an object' error occured' oDoc.SaveAs(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)On this Line ...

Access Denided
Written by Alexandre Paixao on March 31, 2006

Congratulations.I have the problem. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception ...

Follow us on twitter Subscribe to our RSS feed
Activate your free membership today | Login | Currency