Accessing Word through ASP.NET
I am faced with a new requirement in ASP.Net. The requirement is like this : 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(into a network folder). The generated reports are to be sent to their customer by our client.
This is like generating word report. Here I am using find and replace concept to meet the requirement. Just go through the code you can easily understand it.
using System;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Demo
{
/// <summary>
/// Summary description for WordHelper.
/// </summary>
public class WordHelper : MarshalByRefObject
{
private Microsoft.Office.Interop.Word.Application oWord;
AuditLog al = new AuditLog();
public WordHelper()
{
//
// TODO: Add constructor logic here
//
CreateWord();
}
private void CreateWord()
{
try
{
GC.Collect(); //Release if any word instances running...
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;
oWord.Visible = false;
}
catch(Exception ex)
{
al.Add(ex.Message,"CreateWord()", ex.StackTrace);
throw(ex);
}
}
private void CloseWord()
{
Object oMiss = Type.Missing;
try
{
if(oWord != null)
{
oWord.Quit(ref oMiss, ref oMiss,ref oMiss);
Marshal.ReleaseComObject (oWord);
oWord = null;
GC.Collect();
}
}
catch(Exception ex)
{
al.Add("Error while releasing the word object","CloseWord: "+ex.Message,ex.StackTrace);
throw new Exception("Error while closing the word");
}
}
/// <summary>
/// It returns the template directory which contain welcome and claim letter templates
/// </summary>
/// <returns></returns>
private string GetTemplatesDirectory(int planType)
{
SystemSettingDetails ssd = new SystemSettingDetails();
ssd.GetSystemSettingDetails();
try
{
string strRoot = "", strDirPath = "", strSecType = "";
if(ssd.SystemSettings != null)
strRoot = ssd.GetValue("DocumentLibraryPath").ToString();
else
{
ssd.GetSystemSettingDetails();
strRoot = ssd.GetValue("DocumentLibraryPath").ToString();
}
strRoot.Replace("/","\\");
if(!strRoot.Trim().EndsWith("\\"))
{
strRoot = strRoot+ "\\";
}
if(@strRoot.Trim().EndsWith(@"\\"))
{
strRoot.Substring(0,strRoot.Length-2);
}
if(planType == 3)
strSecType = "Section132";
else
strSecType = "Section125";
strDirPath = strRoot + "\\Templates\\" + strSecType ;
return strDirPath;
}
catch(Exception ex)
{
al.Add(ex.Message,"GetTemplatesDirectory()",ex.Sta ckTrace);
throw(ex);
}
}
/// <summary>
/// Gets the Renewal document libary path
/// </summary>
/// <param name="planType">Type of Plan</param>
/// <returns>path</returns>
private string GetRenewalDirectory(int planType)
{
SystemSettingDetails ssd = new SystemSettingDetails();
ssd.GetSystemSettingDetails();
bool success = false;
Impersonation imp = null;
try
{
string strRoot = "", strDirPath = "", strSecType = "";
if(ssd.SystemSettings != null)
strRoot = ssd.GetValue("DocumentLibraryPath").ToString();
else
{
ssd.GetSystemSettingDetails();
strRoot = ssd.GetValue("DocumentLibraryPath").ToString();
}
strRoot.Replace("/","\\");
if(!strRoot.Trim().EndsWith("\\"))
{
strRoot = strRoot+ "\\";
}
if(@strRoot.Trim().EndsWith(@"\\"))
{
strRoot.Substring(0,strRoot.Length-2);
}
if(planType == 3)
strSecType = "Section132";
else
strSecType = "Section125";
strDirPath = strRoot + "\\Renewal\\" + strSecType ;
imp = new Impersonation();
success = imp.Impersonate();
DirectoryInfo dir = new DirectoryInfo( strRoot +"\\Renewal");
if (!dir.Exists)
dir.Create();
dir = new DirectoryInfo(strRoot + "\\renewal\\"+strSecType);
if (!dir.Exists)
dir.Create();
return strDirPath;
}
catch(Exception ex)
{
al.Add(ex.Message,"GetRenewalDirectory()",ex.Stack Trace);
throw(ex);
}
finally
{
if (success) imp.UndoImpersonation();
//CloseWord();
}
}
/// <summary>
/// Generates new plan document , used in plan renewal
/// </summary>
/// <returns>success or failure</returns>
public bool CreateNewPlanDocs(int planType,string CoCode,string CoName,DateTime PlanYearStart,DateTime planYearEnd ,int gracePeriod,string Max1,string Max2,bool IsPrem,string FileName)
{
string StrFileName;
if (planType==1)
StrFileName = "enroll form(125).doc";
else
StrFileName = "enroll form(132).doc";
string tmplDirPath="";
string strPlanYearStart=PlanYearStart.ToString("MMMM") + " " + PlanYearStart.Day.ToString() + ", " + PlanYearStart.Year.ToString();
string strPlanYearEnd=planYearEnd.ToString("MMMM") + " " + planYearEnd.Day.ToString() + ", " + planYearEnd.Year.ToString(); ;
DateTime graceDate = planYearEnd.AddDays(gracePeriod);
string strPlanYearWithGrace = graceDate.ToString("MMMM") + " " + graceDate.Day.ToString() + ", " + graceDate.Year.ToString();
/*get the path to the directory that contains
* welcome and claim letter templates
* based on plan type */
bool success = false;
Impersonation imp = null;
try
{
tmplDirPath = GetTemplatesDirectory(planType);
DirectoryInfo dirInfo = new DirectoryInfo(tmplDirPath);
/*customize the claim and welcome letters and
* print all the file that are in the directory*/
imp = new Impersonation();
success = imp.Impersonate();
FileInfo[] finfo = dirInfo.GetFiles("*.doc");
if(finfo.Length > 0)
{
if (oWord==null)
CreateWord();
}
}
catch (Exception ex)
{
al.Add("CreateNewPlanDocs() : Access Problem in :"+tmplDirPath,ex.Message,ex.StackTrace.ToString() );
return false;
}
finally
{
if (success) imp.UndoImpersonation();
//CloseWord();
}
if(oWord == null)
{
oWord = new Microsoft.Office.Interop.Word.Application();
}
object M =Type.Missing;
//bool isPrintable = false;
object SaveChanges = WdSaveOptions.wdSaveChanges;
Microsoft.Office.Interop.Word.Document oDoc;
object V = tmplDirPath +"\\"+ StrFileName; //Convert to Object..
object I = false; //Convert to Object
object breadonly =true;
string strEnroll = "enroll";
string strWelcome = "welcome";
Microsoft.Office.Interop.Word.Range rng;
Microsoft.Office.Interop.Word.FormFields flds;
try
{
if(StrFileName.EndsWith(".doc"))
{
imp = new Impersonation(); //Access denied problem
success = imp.Impersonate();
oDoc = oWord.Documents.Open(ref V,ref M,ref breadonly,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M);
rng = (Range)oWord.ActiveDocument.Range(ref M,ref M);
flds = rng.FormFields;
/*
* if filename contains the word "Enroll" considered as Enroll letter.
* */
if( StrFileName.ToLower().IndexOf(strEnroll) != -1)
{
/*
* customize the enroll letter.
* */
foreach(FormField f in flds)
{
if(f.Name == "Text1" )
f.Result = CoName;
if(f.Name == "Text2" )
f.Result = strPlanYearStart; // PLan Start
if(f.Name == "Text3" )
f.Result = strPlanYearEnd; if(f.Name == "Text4" )
f.Result = Max1;
if(f.Name == "Text5" )
f.Result = Max2;
//isPrintable = false;
}
// To Remove the Premium table if not selected.
if (!IsPrem)
{
oWord.ActiveDocument.Tables[2].Delete();
}
}
/*
* if filename contains the word "welcome" considered as welcome letter.
* */
if( StrFileName.ToLower().IndexOf(strWelcome)!= -1)
{
/*
* customize the welcome letter.
* */
foreach(FormField f in flds)
{
if(f.Name == "Text1" )
f.Result = CoName;
else if(f.Name == "Text2" )
f.Result = CoCode;
else if(f.Name == "Text3" )
f.Result = strPlanYearStart;
else if(f.Name == "Text4" )
f.Result = strPlanYearEnd;
else if(f.Name == "Text5" )
f.Result = gracePeriod.ToString();
else if(f.Name == "Text6" )
f.Result = strPlanYearEnd; // End + Garce
else if(f.Name == "Text7" )
f.Result = strPlanYearEnd;
//isPrintable = false;
//oDoc.SaveAs(ref dest,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,true,ref M,ref M,ref M,ref M,ref M,ref M);
//TODO : still some forms must be customized, waiting for Sadiq clarification.
}
}
object F = true;
object dest = GetRenewalDirectory(planType) + "\\" + FileName;
try
{
//Change the logged on user
//imp = new Impersonation();
//success = imp.Impersonate();
oDoc.SaveAs(ref dest,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M);
// if(isPrintable)
// oWord.PrintOut(ref I,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M,ref M);
// else
// //oWord.
oDoc.Close(ref SaveChanges, ref M, ref M);
}
catch (Exception ex)
{
al.Add("WordHelper :CreateNewPlan"+StrFileName,ex.Message,ex.StackTra ce.ToString());
//CloseWord();
return false;
}
finally
{
if (success) imp.UndoImpersonation();
CloseWord();
}
}
else
{
al.Add("Not a valid document :"+StrFileName,"CreateNewPlanDocs()","Please remove unnecessay document in the foloder except word templates");
CloseWord();
return false;
}
}
catch(Exception ex)
{
al.Add(ex.Message,"CreateNewPlanDocs : Error while generating document"+FileName,ex.StackTrace);
CloseWord();
return false;
}
finally
{
if (success) imp.UndoImpersonation();
CloseWord();
}
return true;
}
}
}
|