Click here to Skip to main content
11,638,173 members (73,510 online)
Click here to Skip to main content

"There is insufficient memory or disk space. Save the document now" - Opening MS Word from ASP.NET

, 5 Oct 2005 58.5K 29
Rate this:
Please Sign up or sign in to vote.
This article will help you to open an MS-Word Document (Document or Document template) or MS-Excel sheet from server side code (ASP.NET) with minimum configuration efforts.

Introduction

People are often using/opening Ms-Word or MS-Excel based on the requirements in their web application. However opening a Word document from client side script is much easier for developers but in the client browsers we are not sure whether the Active-x components are enabled or not. Moreover it's ad hoc to enable the Active-X components in client browsers. To avoid these chaos we require to handle this operation from server side (ASP.NET). Due to security issues we are always used to getting this error: "There is insufficient memory or disk space. Save the document now", when opening a Word document or template file from ASP.NET.

This article will help you to open an MS-Word Document (Document or Document template) or MS-Excel sheet from server side code with minimum configuration efforts. For my requirement I am using this code as a reusable DLL (in VB.NET) and calling it from ASP.NET.

Source Code

Code in VB.NET (DLL)

Option Explicit Off
Imports System.Data
Imports System
Imports Microsoft.Office.Interop.Word 

Namespace Wordclass 

Public Class WordClass 
'Purpose: This createword function is to open
'the Template.dot (Word Template) file and 
'save this document as DetailDocument.doc then user will
'be redirected  to the DetailDocument.doc page where 
'the user can open or save the document in to their local machine.
'Function Name:Create Word
'Scope Public
'Parameters: 
 '1.str_FilePath-Template.dot file path which
 '     resides in Web.config and taken dynamically
 '2.str_server_Path-URL of the Application
 '3.dsPutDetails-Dataset Which is populating values
 '       from different Tables and writing
 '       the contents in to word document.
 'Return Type:Boolean 
  Public Function CreateWord(ByVal str_FilePath As String, _
       ByVal str_Server_Path As String, _
       ByVal dsPutDetails As DataSet) As Boolean
            
    Dim oWord As New Microsoft.Office.Interop.Word.Application
    Dim oDoc As New Microsoft.Office.Interop.Word.Document 
    Try 
      obj_FileDelete = CreateObject("Scripting.FileSystemObject")
      If obj_FileDelete.FileExists(str_FilePath & "SaveDetails.doc") Then
        obj_FileDelete.DeleteFile(str_FilePath & "SaveDetails.doc")
      End If 

      'We used to get error while executing
      'the next line which is opening the word template 
      oDoc = oWord.Documents.Open(str_FilePath & "Template.dot") 
      If Not IsNothing(dsPutDetails) Then
        If dsPutDetails.Tables.Count <> 0 Then 
          If dsPutDetails.Tables("Search_Result").Rows.Count > 0 Then
            oDoc.lblname.Caption = _
              dsPutDetails.Tables("Search_Result").
                    Rows(0)("appl_name").ToString()
            oDoc.lblid.Caption = _
              dsPutDetails.Tables("Search_Result").
                       Rows(0)("app_id").ToString()
            oDoc.lbltype.Caption = _
              dsPutDetails.Tables("Search_Result").
                     Rows(0)("app_type").ToString()
            oDoc.lblcriticality.Caption = _
              dsPutDetails.Tables("Search_Result").
                     Rows(0)("app_crit").ToString()
            oDoc.lblarchitecture.Caption = _
              dsPutDetails.Tables("Search_Result").
                Rows(0)("app_arch_type").ToString()
            oDoc.lbltestcases.Caption = _
              dsPutDetails.Tables("Search_Result").
                    Rows(0)("test_case").ToString()
            oDoc.lblniface.Caption = _
              dsPutDetails.Tables("Search_Result").Rows(0)
                ("app_no_of_interfaces").ToString()
            oDoc.lblbownername.Caption = _
              dsPutDetails.Tables("Search_Result").
                   Rows(0)("b_own_name").ToString()
            oDoc.lblbownerph.Caption = _
              dsPutDetails.Tables("Search_Result").
                  Rows(0)("b_own_phone").ToString()
            oDoc.lblbowneremail.Caption = _
              dsPutDetails.Tables("Search_Result").
                 Rows(0)("b_own_email").ToString()
            oDoc.lbltownername.Caption = _
              dsPutDetails.Tables("Search_Result").
                 Rows(0)("t_own_name").ToString()
            oDoc.lbltownerph.Caption = _
              dsPutDetails.Tables("Search_Result").
                 Rows(0)("t_own_phone").ToString()
            oDoc.lbltowneremail.Caption = _
              dsPutDetails.Tables("Search_Result").
                 Rows(0)("t_own_email").ToString()
          End If
        End If
      End If
      oDoc.SaveAs(str_FilePath & "SaveDetails.doc")
      'Return True 
    Catch ex As Exception 
    Finally
        oDoc.Close(False)
        oWord.Quit()
        oDoc = Nothing
        oWord = Nothing
    End Try 
  End Function
End Class
End Namespace
'Add this WordClassLib as a reference 
'in your ASP.NET application

Calling from ASP.NET (code behind as C#)

using WordClassLib.Wordclass;
/* "Event for Export to word document"*/
private void btnExptoWord_Click(object sender,System.EventArgs e)
{
  private DataSet ds_DBSearch = new DataSet("Ds_Worddetails");

  /*Fill and populate the DS_Worddetails dataset from the table in your database*/

  //Instantiating object for VBDLL WordClass
  WordClass ObjWord = new WordClass();
  try
  {
    //Getting the WordFile Path from Web.config
    //Calling Creatword function and passing 
    //all the required parameters
    ObjWord.CreateWord(ConfigurationSettings.AppSettings.Get(
       "WordFile").ToString(),str_ServerPath,ds_WordDetails); 
  }
  catch(Exception Ex)
  {
    Errorlog.ErrorLog objErr=new Errorlog.ErrorLog();
    if (objErr.LogErrorToDB("Error while export to word ",Ex,"")==true) 
      objErr=null;
    Response.Write("<script text = 'javascript'>" + 
       "parent.location.href = '"+str_ServerPath+
       "/Error.aspx'</script>");
  }
  finally
  {
    ObjWord=null;
  }
  Response.Redirect(str_ServerPath + "/SaveDetails.doc");
}
/***************************************/
/*If you run the application you will get an error 
"There is insufficient memory or disk space.save 
the document now" while opening the word document 
This is because of high level security  in ASP.NET, 
so we need to impersonate the user who is launching 
the application in web.config
*/

Configuration settings in web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    
  <system.web> 
    <compilation 
         defaultLanguage="c#"
         debug="true"
    /> 
    <customErrors 
    mode="RemoteOnly" 
    /> 
    <authentication mode="Windows" /> 
    <authorization>
        <allow users="*" /> <!--<span class="code-comment"> Allow all users --></span>
    </authorization> 
    <trace
        enabled="false"
        requestLimit="10"
        pageOutput="false"
        traceMode="SortByTime"
        localOnly="true"
    /> 
    <sessionState 
            mode="InProc"
            stateConnectionString="tcpip=127.0.0.1:42424"
            sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
            cookieless="false" 
            timeout="30" 
    /> 
 
 
    <!--<span class="code-comment">  GLOBALIZATION
          This section sets the globalization settings of the application. 
    --></span>
    <globalization 
            requestEncoding="utf-8" 
            responseEncoding="utf-8" 
   />
<!--<span class="code-comment"> Here we have to put the impersonation section 
         to identity the user for this application--></span>
<identity impersonate="true" 
          userName="Domain or ComputerName\UserName" password="Password"/>
   </system.web>
 <appSettings>
<!--<span class="code-comment"> Database connection information--></span>
     <add key = "ConnString" value="Provider=SQLOLEDB.1;Persist Security 
                    Info=False;User ID=username;Password = password;
                    Initial Catalog=DatabaseName;Data Source=DatabaseServerName" />

<!--<span class="code-comment">File Path for Word Template--></span>
  
    <add key = "WordFile" value="C:\inetpub\wwwroot\appname\" />
 </appSettings>

</configuration>
--After adding this section in web.config run the application, 
--now u can successfully open the document from ASP.NET application.

Conclusion

This code is evaluated and tested on Windows XP, 2000 and also in Windows 2003. Only impersonating the user in web.config to this application is enough, no need to configure Microsoft Word Component under component services (Dcomcnfg.exe). Hope this article will help you to work on MS Word or MS Excel from ASP.NET. Do let me know if your require any information/queries on this article.

Thank you.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralProblem in understanding Pin
Sami.Qureshi14-Jun-10 2:49
memberSami.Qureshi14-Jun-10 2:49 
GeneralMy vote of 1 Pin
ashisharisgloabal9-Apr-10 3:14
memberashisharisgloabal9-Apr-10 3:14 
GeneralNice solution but I have got some other exception. Pin
Rakesh Bhavsar28-May-09 2:48
memberRakesh Bhavsar28-May-09 2:48 
Questionupdate Pin
SALEHSH16-Feb-07 12:29
memberSALEHSH16-Feb-07 12:29 
QuestionNot always working Pin
Akos Dudas19-Nov-06 0:36
memberAkos Dudas19-Nov-06 0:36 
AnswerRe: Not always working Pin
Johnny Glenn25-Mar-12 22:04
memberJohnny Glenn25-Mar-12 22:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150728.1 | Last Updated 5 Oct 2005
Article Copyright 2005 by Sadish Kumar.V
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid