Wrox Programmer Forums
Go Back   Wrox Programmer Forums > .NET > Other .NET > General .NET
|
General .NET For general discussion of MICROSOFT .NET topics that don't fall within any of the other .NET forum subcategories or .NET language forums.  If your question is specific to a language (C# or Visual Basic) or type of application (Windows Forms or ASP.Net) try an applicable forum category. ** PLEASE BE SPECIFIC WITH YOUR QUESTION ** When posting here, provide details regarding the Microsoft .NET language you are using and/or what type of application (Windows/Web Forms, etc) you are working in, if applicable to the question. This will help others answer the question without having to ask.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the General .NET section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 3rd, 2006, 12:55 PM
Registered User
 
Join Date: May 2006
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to renoldr Send a message via Yahoo to renoldr
Default 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;
        }
    }
}



 
Old May 3rd, 2006, 12:59 PM
Registered User
 
Join Date: May 2006
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to renoldr Send a message via Yahoo to renoldr
Default

I seems to be getting an 'access denied' exception.
i have tried impersonation too but of no positive result. The user is given full access to the network directory. if i removed impersonation it says it cannto find the path (or that path is invalid) even though i can open it thru word.
Help!

 
Old December 2nd, 2013, 06:58 AM
Registered User
 
Join Date: Nov 2013
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Default Re: Accessing Word through ASP.NET

If I may suggest you should check out this C# Word component, it will enable you to load your existing template files and do search & replace on them, without using a word interop in .NET.
I believe this is a much safer approach because you will not have to run MS Word on the server side in the background, which has some drawbacks. Also I would recommend you to try using a MergeFields for inserting a data into a DOCX file, here is a sample how to do a mail merge in C#:
Code:
// Create a new empty document.
var template = new DocumentModel();

// Add document content.
template.Sections.Add(
    new Section(document,
        new Paragraph(document,
            new Field(document, FieldType.MergeField, "FullName"))));

// Save the template document.
template.Save(strRoot + "\\Templates\\TemplateDocument.docx");

// Load a template document.
var document = DocumentModel.Load(strRoot + "\\Templates\\TemplateDocument.docx");

// Initialize mail merge data source.
var dataSource = new { FullName = "John Doe" };

// Execute mail merge.
document.MailMerge.Execute(dataSource);

// Save the document.
document.Save("Document.docx");
Also you can export a Word file in ASP.NET to the customer’s browser like the following:
Code:
document.Save(this.Response, "Document.docx");

Last edited by RedDotVasilyev; December 2nd, 2013 at 07:06 AM..





Similar Threads
Thread Thread Starter Forum Replies Last Post
accessing files from asp.net naidukap ASP.NET 1.0 and 1.1 Professional 1 November 18th, 2005 08:59 AM
Accessing WORD object in ASP mcinar Classic ASP Basics 5 March 30th, 2005 04:19 PM
Accessing ASP Application Object from .NET yuvalk ASP.NET 1.x and 2.0 Application Design 2 July 19th, 2004 10:29 AM
Accessing .asp cookie from ASP.net ksams General .NET 4 July 7th, 2004 02:34 AM
Accessing Word Object Library from .NET Web app debsoft General .NET 3 April 21st, 2004 05:53 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.