Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

XML/XSLT Word Report Generator

, 11 Jan 2009 CPOL
The tool is based on XML/XSLT, and allows a user to create a Word report from scratch, namely: construct SQL query, construct a WordML template, generate a document.
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using System.Data;
using System.Threading;

using Microsoft.Office;
using Microsoft.Office.Core;


namespace WordReportGenerator
{
    public delegate void DelegateLoadDocument(String s, Boolean isxml);
    public delegate void DelegateThreadFinished();

    internal class WordApp
    {
        private WRGEngine engine;

        ManualResetEvent m_EventStopThread;
        ManualResetEvent m_EventThreadStopped;
        public DelegateLoadDocument m_DelegateLoadDocument;

        private Word.Document document;
        private Word.ApplicationClass wd = null;
        public CommandBars oCommandBars;
        public CommandBar AddInCommandBar;
        public CommandBarButton AddInOpen;
        public CommandBarButton AddInSave;
        public CommandBarButton AddInGenerate;
        object missing = System.Reflection.Missing.Value;

        public WordApp(ref Object value) {

            if (value is WRGEngine)
                engine = (WRGEngine)value;

            m_DelegateLoadDocument = new DelegateLoadDocument(this.LoadDocument);
            m_EventStopThread = new ManualResetEvent(false);
            m_EventThreadStopped = new ManualResetEvent(false);
        }

        private void OnQuit()
        {
            wd = null;
        }

        public void InitWord()
        {
            string tag;
            IEnumerator pos;

            if (wd == null) wd = new Word.ApplicationClass();
            try
            {
                wd.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);
            }
            catch { }


            #region CommandBar

            try
            {
                oCommandBars = (CommandBars)wd.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, wd, null);
                object cbname = "WRGenerator";
                pos = oCommandBars.GetEnumerator();
                while (pos.MoveNext())
                {
                    try
                    {
                        if (!((CommandBar)pos.Current).BuiltIn && ((CommandBar)pos.Current).NameLocal == "WRGenerator")
                            AddInCommandBar = (CommandBar)pos.Current;
                    }
                    catch { }
                }
                if (AddInCommandBar == null)
                {
                    AddInCommandBar = oCommandBars.Add(cbname, missing, missing, missing);
                    AddInCommandBar.NameLocal = "WRGenerator";
                }

                try
                {
                    pos = AddInCommandBar.Controls.GetEnumerator();
                    while (pos.MoveNext())
                    {
                        try
                        {
                            tag = ((CommandBarButton)pos.Current).Tag;
                            if (tag == "AddInOpen")
                                AddInOpen = (CommandBarButton)pos.Current;
                            else if (tag == "AddInSave")
                                AddInSave = (CommandBarButton)pos.Current;
                            else if (tag == "AddInGenerate")
                                AddInGenerate = (CommandBarButton)pos.Current;
                        }
                        catch { }
                    }
                    if (AddInOpen == null)
                    {
                        AddInOpen = (CommandBarButton)AddInCommandBar.Controls.Add(1, missing, missing, missing, missing);
                        AddInOpen.Caption = "Open template";
                        AddInOpen.Style = MsoButtonStyle.msoButtonCaption;
                        AddInOpen.Tag = "AddInOpen";
                        AddInOpen.OnAction = "!<" + WRG._assemblyName + ".Connect>";
                    }
                    AddInOpen.Click += new _CommandBarButtonEvents_ClickEventHandler(this.AddInOpen_click);
                    if (AddInSave == null)
                    {
                        AddInSave = (CommandBarButton)AddInCommandBar.Controls.Add(1, missing, missing, missing, missing);
                        AddInSave.Caption = "Save template";
                        AddInSave.Style = MsoButtonStyle.msoButtonCaption;
                        AddInSave.Tag = "AddInSave";
                        AddInSave.OnAction = "!<" + WRG._assemblyName + ".Connect>";
                    }
                    AddInSave.Click += new _CommandBarButtonEvents_ClickEventHandler(this.AddInSave_click);
                    if (AddInGenerate == null)
                    {
                        AddInGenerate = (CommandBarButton)AddInCommandBar.Controls.Add(1, missing, missing, missing, missing);
                        AddInGenerate.Caption = "Generate report";
                        AddInGenerate.Style = MsoButtonStyle.msoButtonCaption;
                        AddInGenerate.Tag = "AddInGenerate";
                        AddInGenerate.OnAction = "!<" + WRG._assemblyName + ".Connect>";
                    }
                    AddInGenerate.Click += new _CommandBarButtonEvents_ClickEventHandler(this.AddInGenerate_click);

                    AddInOpen.Visible = true;
                    AddInSave.Visible = true;
                    AddInGenerate.Visible = true;
                    AddInCommandBar.Visible = true;
                }
                catch{ }
            }
            catch{ }

            #endregion

            AddInCommandBar = null;
        }

        public void LoadDocument(string t_filename, bool isXml)
        {

            if (document != null)
            {
                try
                {
                    object dummy = null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            object fileName = t_filename;
            object newTemplate = false;
            object docType = 0;
            object readOnly = true;
            object isVisible = true;
            try
            {
                if (wd == null)
                {
                    throw new WordInstanceException();
                }

                if (wd.Documents == null)
                {
                    throw new DocumentInstanceException();
                }

                if (wd != null && wd.Documents != null)
                {
                    document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                }

                if (document == null)
                {
                    throw new ValidDocumentException();
                }
            }
            catch
            {
            }

            #region Xml Schema

            object schema = engine.xmlSchemaName;
            object alias = engine.xmlSchemaAlias;
            object schemafilename = WRG._path + "//" + engine.xmlSchemaFileName + ".xsd";
            object active = wd.ActiveDocument;
            try
            {
                //wd.Activate();
                if (wd.XMLNamespaces.Count > 0)
                {
                    foreach (Word.XMLNamespace ns in wd.XMLNamespaces)
                        if (engine.isupdate && ns.URI == engine.xmlSchemaName && ns.get_Alias(true) == engine.xmlSchemaAlias)
                            ns.Delete();
                }
                if (engine.xmlSchemaName != "" && engine.xmlSchemaAlias != "" && engine.xmlSchemaFileName != "")
                {
                    if (engine.isupdate)
                        try
                        {
                            wd.ActiveDocument.XMLSchemaReferences.Add(ref schema, ref alias, ref schemafilename, true);
                        }
                        catch (Exception ex) { MessageBox.Show(ex.Message); }
                        finally { engine.isupdate = false; }
                }
                foreach (Word.XMLNamespace ns in wd.XMLNamespaces)
                    if (ns.get_Alias(true) == engine.xmlSchemaAlias)
                        ns.AttachToDocument(ref active);

                wd.ActiveWindow.View.ShowXMLMarkup = isXml ? 1 : 0;
                wd.ActiveDocument.XMLSchemaReferences.AllowSaveAsXMLWithoutValidation = true;
                wd.TaskPanes[Word.WdTaskPanes.wdTaskPaneXMLStructure].Visible = isXml ? true : false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            #endregion

            wd.Visible = true;
        }

        //-------------------------

        public void AddInGenerate_click(CommandBarButton cmdBarbutton, ref bool cancel)
        {
            if (!engine.GetXml())
                    return;

            if (engine.xslt == String.Empty)
                if (!engine.GetXslt())
                    return;

            byte[] wordDoc = engine.GetWord();
            if (wordDoc == null)
                return;
            using (FileStream fs = new FileStream(WRG._path + "//" + "tmp.doc", FileMode.Create))
                fs.Write(wordDoc, 0, wordDoc.Length);
            LoadDocument(WRG._path + "//" + "tmp.doc", true);
        }

        public void AddInSave_click(CommandBarButton cmdBarbutton, ref bool cancel){
            string templateFileName = WRG._path + "//" + "word.xml";
            if (wd != null && wd.Application.Documents.Count > 0 && wd.Application.ActiveDocument != null)
            {
                try{
                    object oSaveFormat = (object)Word.WdSaveFormat.wdFormatXML;
                    object oFileName = (object)templateFileName;
                    wd.Application.ActiveDocument.SaveAs(
                        ref oFileName,
                        ref oSaveFormat,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing);

                    FileStream fs = new FileStream(templateFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    using(StreamReader sr = new StreamReader(fs))
                    engine.wml = sr.ReadToEnd();
                }
                catch (Exception ex){
                    MessageBox.Show(ex.Message);
                }
            }
        }

        public void AddInOpen_click(CommandBarButton cmdBarbutton, ref bool cancel)
        {
            if (!engine.GetWml())
                return;
            LoadDocument(WRG._path + "//" + "word.xml", true);
        }

        //-------------------------

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sam Safonov
Software Developer
Russian Federation Russian Federation
I have Master degree in Particle Physics. During my last several years I work as software developer.
 
Primary Interests
- c#, c++, php, java.
- scientific programming

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 11 Jan 2009
Article Copyright 2009 by Sam Safonov
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid