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
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
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")
Catch ex As Exception
Finally
oDoc.Close(False)
oWord.Quit()
oDoc = Nothing
oWord = Nothing
End Try
End Function
End Class
End Namespace
Calling from ASP.NET (code behind as C#)
using WordClassLib.Wordclass;
private void btnExptoWord_Click(object sender,System.EventArgs e)
{
private DataSet ds_DBSearch = new DataSet("Ds_Worddetails");
WordClass ObjWord = new WordClass();
try
{
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");
}
Configuration settings in web.config
="1.0" ="utf-8"
<configuration>
<system.web>
<compilation
defaultLanguage="c#"
debug="true"
/>
<customErrors
mode="RemoteOnly"
/>
<authentication mode="Windows" />
<authorization>
<allow users="*" /> -->
</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"
/>
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>
-->
<identity impersonate="true"
userName="Domain or ComputerName\UserName" password="Password"/>
</system.web>
<appSettings>
-->
<add key = "ConnString" value="Provider=SQLOLEDB.1;Persist Security
Info=False;User ID=username;Password = password;
Initial Catalog=DatabaseName;Data Source=DatabaseServerName" />
-->
<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.