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.Xml;
using System.Xml.Xsl;
using System.Data;
using System.ComponentModel;
using System.Drawing.Design;

using WRG.xslt;

namespace WordReportGenerator
{
    [TypeConverter(typeof(PropertySorter))]
    public class WRGEngine : FilterablePropertyBase,INotifyPropertyChanged
    {

        private WordApp word_app;

        public event PropertyChangedEventHandler PropertyChanged;

        private Boolean Active = true;
        public Boolean autoset = true;
        private PropertyGrid _pg;
        private DataGridView _gv;

        private int _oid;
        private string _title;
        private string _sql;
        private string _xsd;
        private string _wml;
        private string _xslt;
        private string _xml;
        private string _xmlSchemaName;
        private string _xmlSchemaAlias;
        private string _xmlSchemaFileName;
        public Boolean isupdate;

        #region Properties

        [Browsable(false)]
        public int oid
        {
            get { return _oid; }
            set
            {
                _oid = value;
                if (Active && _oid > 0)
                    LoadData(_oid);
            }
        }
        [DisplayName("Title")]
        [Description("Title")]
        [Category("1. Settings")]
        [PropertyOrder(1)]
        public string title
        {
            get { return _title; }
            set { _title = value; FirePropertyChangedNotification("title"); }
        }
        [DisplayName("Namespace")]
        [Description("�������� �����")]
        [Category("1. Settings")]
        [PropertyOrder(4)]
        public string xmlSchemaName
        {
            get { return _xmlSchemaName; }
            set { _xmlSchemaName = value; FirePropertyChangedNotification("xmlSchemaName"); }
        }
        [DisplayName("Alias")]
        [Description("Alias")]
        [Category("1. Settings")]
        [PropertyOrder(5)]
        public string xmlSchemaAlias
        {
            get { return _xmlSchemaAlias; }
            set { _xmlSchemaAlias = value; FirePropertyChangedNotification("xmlSchemaAlias"); }
        }
        [DisplayName("Path to XMLScheme(.xsd) file")]
        [Description("Path to XMLScheme(.xsd) file")]
        [Category("1. Settings")]
        [PropertyOrder(6)]
        public string xmlSchemaFileName
        {
            get { return _xmlSchemaFileName; }
            set { _xmlSchemaFileName = value; FirePropertyChangedNotification("xmlSchemaFileName"); }
        }
        [DisplayName("SQL")]
        [Description("SQL")]
        [Category("1. Settings")]
        [Editor(typeof(TextEditor), typeof(UITypeEditor))]
        [PropertyOrder(7)]
        public string sql
        {
            get { return _sql; }
            set
            {
                _sql = value;
                if (autoset)
                    this.autoSetProperties();
                FirePropertyChangedNotification("sql");
                GetXml();
                GetXsd();
                isupdate = true;
                this.wml = String.Empty;
                this.xslt = String.Empty;
            }
        }
        [DisplayName("XSD")]
        [Description("XSD")]
        [Category("1. Settings")]
        [Editor(typeof(TextEditor), typeof(UITypeEditor))]
        [PropertyOrder(8)]
        public string xsd
        {
            get { return _xsd; }
            set
            {
                _xsd = value; FirePropertyChangedNotification("xsd");
            }
        }
        [DisplayName("WordML")]
        [Description("WordML")]
        [Category("1. Settings")]
        [Editor(typeof(TextEditor), typeof(UITypeEditor))]
        [PropertyOrder(9)]
        public string wml
        {
            get { return _wml; }
            set
            {
                _wml = value; 
                FirePropertyChangedNotification("wml");
                this.xslt = String.Empty;
            }
        }
        [DisplayName("XSLT")]
        [Description("XSLT")]
        [Category("1. Settings")]
        [Editor(typeof(TextEditor), typeof(UITypeEditor))]
        [PropertyOrder(10)]
        public string xslt
        {
            get { return _xslt; }
            set
            {
                _xslt = value;
                FirePropertyChangedNotification("xslt");
            }
        }
        [Browsable(false)]
        public string xml
        {
            get { return _xml; }
            set { _xml = value; }
        }
        [Browsable(false)]
        public DataGridView gv
        {
            get { return _gv; }
            set 
            { 
                _gv = value;
                this.TranslateHeaders();
            }
        }
        [Browsable(false)]
        public PropertyGrid pg
        {
            get { return _pg; }
            set { _pg = value; }
        }

        private DataRowView _c;
        [Browsable(false)]
        public DataRowView c{
            get 
            { 
                _c = (DataRowView)WRG.dal.bs_wordreports.Current; 
                return _c; 
            }
        }

        #endregion

        public WRGEngine(){
            WRG.dal.bs_wordreports.PositionChanged += new EventHandler(bs_PositionChanged);
            PropertyChanged += new PropertyChangedEventHandler(pg_PropertyChanged);
        }

        private void TranslateHeaders()
        {
            DataGridViewColumn c;
            int count = _gv.Columns.Count;

            if (_gv != null)
            {
                for (int i = 0; i < count; i++)
                {
                    c = _gv.Columns[i];
                    switch (c.Name)
                    {
                        case "oid":
                        case "sql":
                        case "xsd":
                        case "wml":
                        case "xslt":
                        case "Ins":
                        case "Upd":
                        case "xml":
                        case "isupdate":
                        case "xmlns":
                        case "xmlalias":
                        case "xmlfilename":
                            c.Visible = false; break;
                        default: break;
                    }
                }
            }
        }
        public void bs_PositionChanged(Object sender, EventArgs e){
            if (Active){
                LoadData();
                if (_pg != null)
                    _pg.Refresh();
            }
        }
        public void FirePropertyChangedNotification(string propName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
        public void pg_PropertyChanged(Object sender, PropertyChangedEventArgs e)
        {
            if (c != null)
            {
                if (e.PropertyName == "title")
                    _c[e.PropertyName] = this._title;
                else if (e.PropertyName == "sql"){
                    _c[e.PropertyName] = this._sql;
                }
                else if (e.PropertyName == "xsd")
                {
                    _c[e.PropertyName] = this._xsd;
                }
                else if (e.PropertyName == "wml")
                {
                    _c[e.PropertyName] = this._wml;
                    WRG.dal.Update("wordreports");
                }
                else if (e.PropertyName == "xstl")
                {
                    _c[e.PropertyName] = this._xslt;
                    WRG.dal.Update("wordreports");
                }
                else if (e.PropertyName == "xmlSchemaName")
                    _c["xmlns"] = this._xmlSchemaName;
                else if (e.PropertyName == "xmlSchemaAlias")
                    _c["xmlalias"] = this._xmlSchemaAlias;
                else if (e.PropertyName == "xmlSchemaFileName")
                    _c["xmlfilename"] = this._xmlSchemaFileName;

                WRG.dal.bs_wordreports.EndEdit();
            }
        }
        public void LoadData(int oid)
        {
            Active = false;
            WRG.dal.bs_wordreports.Position = WRG.dal.bs_wordreports.Find("oid", oid);
            LoadData();
            Active = true;
        }
        public void LoadData()
        {
            if (c != null)
            {
                _oid = (_c["oid"].Equals(DBNull.Value)) ? 0 : (Int32)_c["oid"];
                _title = _c["title"].ToString();
                _sql = _c["sql"].ToString();
                _xsd = _c["xsd"].ToString();
                _wml = _c["wml"].ToString();
                _xslt = _c["xslt"].ToString();
                _xmlSchemaName = _c["xmlns"].ToString();
                _xmlSchemaAlias = _c["xmlalias"].ToString();
                _xmlSchemaFileName = _c["xmlfilename"].ToString();
            }
        }
        public void autoSetProperties()
        {
            char[] delim;
            string[] parts;

            try
            {
                delim = ((System.String)"'").ToCharArray();
                parts = this._sql.Split(delim);
                this.xmlSchemaName = parts[1];
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            try
            {
                delim = ((System.String)"\\/").ToCharArray();
                parts = this.xmlSchemaName.Split(delim);
                this._xmlSchemaAlias = parts[parts.Length - 1];
                delim = ((System.String)".").ToCharArray();
                parts = this.xmlSchemaAlias.Split(delim);
                this.xmlSchemaAlias = parts[0];
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            try
            {
                delim = ((System.String)"\\/").ToCharArray();
                parts = this.xmlSchemaName.Split(delim);
                this._xmlSchemaFileName = parts[parts.Length - 1];
                delim = ((System.String)".").ToCharArray();
                parts = this.xmlSchemaFileName.Split(delim);
                this.xmlSchemaFileName = parts[0];
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }

        }

        public Boolean GetXml(){
            try
            {
                this.xml = (string)WRG.dal.ExecuteScalar(_sql);
            }
            catch (Exception ex) 
            { 
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }

        public Boolean GetXsd(){
            XmlDataDocument doc = new XmlDataDocument();
            XmlReader xmlData;

            try
            {
                xmlData = XmlReader.Create(new StringReader(xml));
                doc.DataSet.ReadXml(xmlData);
                doc.DataSet.WriteXmlSchema(WRG._path + "//" + _xmlSchemaFileName + ".xsd");
                using (StreamReader sr = new StreamReader(WRG._path + "//" + _xmlSchemaFileName + ".xsd"))
                    xsd = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }

        public Boolean GetWml(){
            try
            {
                FileStream fs = new FileStream(WRG._path + "//word.xml", FileMode.Create);
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                    sw.WriteLine(_wml);
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }

        public Boolean GetXslt()
        {
            Wml2xslt converter = new Wml2xslt();
            StringBuilder sb = new StringBuilder();
            XmlWriter w = XmlWriter.Create(sb);
            XmlReader r = XmlReader.Create(new StringReader(wml));
            try
            {
                converter.Execute(r, w, this._xmlSchemaName);
                xslt = sb.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }
        
        public byte[] GetWord()
        {
            XmlReader xsltReader;
            XmlReader xmlData;
            XslCompiledTransform gw_xslt;

            using (MemoryStream swResult = new MemoryStream()){
                try
                {
                    gw_xslt = new XslCompiledTransform();
                    xsltReader = XmlReader.Create(new StringReader(xslt));
                    xmlData = XmlReader.Create(new StringReader(xml));

                    gw_xslt.Load(xsltReader);
                    gw_xslt.Transform(xmlData, new XsltArgumentList(), swResult);
                    return swResult.ToArray();
                }
                catch (Exception ex){
                    MessageBox.Show(ex.Message);
                }
            }
            return null;
        }

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

        public void btn_newtemplate_Click(object sender, EventArgs e)
        {
            if (word_app == null)
            {
                Object value = this;
                word_app = new WordApp(ref value);
            }
            
            word_app.InitWord();
            word_app.LoadDocument(String.Empty, true);
        }

        public void btn_loadtemplate_Click(object sender, EventArgs e)
        {
            if (word_app == null)
            {
                Object value = this;
                word_app = new WordApp(ref value);
            }

            if (!GetWml())
                return;
            word_app.InitWord();
            word_app.LoadDocument(WRG._path + "//word.xml", true);
        }

        public void btn_genreport_Click(object sender, EventArgs e)
        {
            if (word_app == null){
                Object value = this;
                word_app = new WordApp(ref value);
            }

            if (!GetXml())
                return;
            if (!GetXslt())
                return;

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

            word_app.InitWord();
            word_app.LoadDocument(WRG._path + "//tmp.doc", false);
        }
    }
}

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
Web04 | 2.8.141220.1 | Last Updated 11 Jan 2009
Article Copyright 2009 by Sam Safonov
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid