XML导出word

新建一个word文档,如图

在相应单元格中插入书签

将word文档另存为xml文档

公共类:

using System;
using System.Collections.Generic;
using System.Xml;
using System.Drawing;
using System.IO;
using System.Data;
using System.Configuration;

namespace Utility
{
    /// <summary>
    /// 导出word
    /// Author:FreezeSoul&Worm
    /// 操作WordML(2003)根据标签插入文本、表格、图片
    /// </summary>
    public class ExportWordML
    {

        /// <summary>
        /// 最短路径图片在导出Word文件中的宽度
        /// webconfig中加入节点 <add key ="WordWidth" value="400"/>
        /// </summary>
        public string WordWidth
        {
            get
            {
                return ConfigurationManager.AppSettings["WordWidth"].ToString();
            }
        }

        /// <summary>
        /// 最短路径图片在导出Word文件中的高度
        /// webconfig中加入节点<add key ="WordHeight" value="300"/>
        /// </summary>
        public string WordHeight
        {
            get
            {
                return ConfigurationManager.AppSettings["WordHeight"].ToString();
            }
        }

        private XmlNamespaceManager nsmgr;
        private XmlDocument xdoc;
        public void CreateXmlDom(string xmlPath)
        {
            xdoc = new XmlDocument();

            xdoc.Load(xmlPath);
            nsmgr = new XmlNamespaceManager(xdoc.NameTable);
            nsmgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");
            nsmgr.AddNamespace("v", "urn:schemas-microsoft-com:vml");
            nsmgr.AddNamespace("aml", "http://schemas.microsoft.com/aml/2001/core");
            nsmgr.AddNamespace("wx", "http://schemas.microsoft.com/office/word/2003/auxHint");
        }

        #region 导出Word文档的方法

        /// <summary>
        /// 设置节点的值
        /// </summary>
        /// <param name="bookmarks"></param>
        public void SetNodeText(Dictionary<string, string> bookmarks)
        {
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                SetBookMarkTexts(xdoc, node, bookmarks);
            }
        }

        /// <summary>
        /// 根据数据集插入数据,数据集中的数据表含有一条数据
        /// </summary>
        /// <param name="ds"></param>
        public void SetNodeTextDataSet(DataSet ds)
        {
            Dictionary<string, string> bookmarkValues = new Dictionary<string, string>();
            foreach (System.Data.DataTable dt in ds.Tables)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    if (dt.Rows.Count > 0)
                    {
                        bookmarkValues.Add(dt.TableName + "_" + dc.ColumnName, dt.Rows[0][dc.ColumnName].ToString());
                    }
                }
            }
            SetNodeText(bookmarkValues);
        }

        /// <summary>
        /// 根据数据表插入数据,数据表含有一条数据
        /// </summary>
        /// <param name="ds"></param>
        public void SetNodeTextDataTable(System.Data.DataTable dt)
        {
            Dictionary<string, string> bookmarkValues = new Dictionary<string, string>();

            foreach (DataColumn dc in dt.Columns)
            {
                if (dt.Rows.Count > 0)
                {
                    bookmarkValues.Add(dt.TableName + "_" + dc.ColumnName, dt.Rows[0][dc.ColumnName].ToString());
                }
            }
            SetNodeText(bookmarkValues);
        }

        /// <summary>
        /// 插入一张表数据,表中含有多条数据
        /// </summary>
        /// <param name="tables"></param>
        public void SetNodeTable(Dictionary<string, System.Data.DataTable> tables)
        {
            Dictionary<string, WordTable> wordtables = new Dictionary<string, WordTable>();

            foreach (KeyValuePair<string, System.Data.DataTable> table in tables)
            {
                wordtables.Add(table.Key, WordTable.GetWordTabelFromDataTable(table.Value));
            }
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                SetBookMarkTablesHorizontal(xdoc, node, wordtables);
            }
        }

        /// <summary>
        /// 插入一张表数据,表中含有多条数据
        /// </summary>
        /// <param name="wordtables"></param>
        public void SetNodeTable(Dictionary<string, WordTable> wordtables)
        {
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                SetBookMarkTablesHorizontal(xdoc, node, wordtables);
            }
        }

        /// <summary>
        /// 插入一张表数据,表中含有多条数据
        /// </summary>
        /// <param name="tables"></param>
        /// <param name="IsHorizontal">是否为水平列表,即列名在数据上方</param>
        public void SetNodeTable(Dictionary<string, System.Data.DataTable> tables, bool IsHorizontal)
        {
            Dictionary<string, WordTable> wordtables = new Dictionary<string, WordTable>();

            foreach (KeyValuePair<string, System.Data.DataTable> table in tables)
            {
                wordtables.Add(table.Key, WordTable.GetWordTabelFromDataTable(table.Value));
            }
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                if (IsHorizontal)
                    SetBookMarkTablesHorizontal(xdoc, node, wordtables);
                else
                    SetBookMarkTablesVertical(xdoc, node, wordtables);
            }
        }

        /// <summary>
        /// 插入一张表数据,表中含有多条数据
        /// </summary>
        /// <param name="wordtables"></param>
        /// <param name="IsHorizontal">是否为水平列表,即列名在数据上方</param>
        public void SetNodeTable(Dictionary<string, WordTable> wordtables, bool IsHorizontal)
        {
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                if (IsHorizontal)
                    SetBookMarkTablesHorizontal(xdoc, node, wordtables);
                else
                    SetBookMarkTablesVertical(xdoc, node, wordtables);
            }
        }

        /// <summary>
        /// 插入一张表数据,表中含有多条数据
        /// 图片的列是传入datatabele的最后一列,且最后一列为图片的绝对地址
        /// </summary>
        /// <param name="tables"></param>
        /// <param name="IsHorizontal">是否为水平列表,即列名在数据上方</param>
        /// <param name="ExistPicture">是否含有图片</param>
        public void SetNodeTable(Dictionary<string, System.Data.DataTable> tables, bool IsHorizontal, bool ExistPicture)
        {
            Dictionary<string, WordTable> wordtables = new Dictionary<string, WordTable>();

            foreach (KeyValuePair<string, System.Data.DataTable> table in tables)
            {
                wordtables.Add(table.Key, WordTable.GetWordTabelFromDataTable(table.Value));
            }
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                if (ExistPicture)
                {
                    if (IsHorizontal)
                        SetBookMarkTablesPictureHorizontal(xdoc, node, wordtables);
                    else
                        SetBookMarkTablesPictureVertical(xdoc, node, wordtables);
                }
                else
                {
                    if (IsHorizontal)
                        SetBookMarkTablesHorizontal(xdoc, node, wordtables);
                    else
                        SetBookMarkTablesVertical(xdoc, node, wordtables);
                }
            }
        }

        /// <summary>
        /// 插入一张表数据,表中含有多条数据
        /// 图片的列是传入wordtables的最后一列,且最后一列为图片的绝对地址
        /// </summary>
        /// <param name="wordtables"></param>
        /// <param name="IsHorizontal">是否为水平列表,即列名在数据上方</param>
        /// <param name="ExistPicture">是否含有图片</param>
        public void SetNodeTable(Dictionary<string, WordTable> wordtables, bool IsHorizontal, bool ExistPicture)
        {
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                if (ExistPicture)
                {
                    if (IsHorizontal)
                        SetBookMarkTablesPictureHorizontal(xdoc, node, wordtables);
                    else
                        SetBookMarkTablesPictureVertical(xdoc, node, wordtables);
                }
                else
                {
                    if (IsHorizontal)
                        SetBookMarkTablesHorizontal(xdoc, node, wordtables);
                    else
                        SetBookMarkTablesVertical(xdoc, node, wordtables);
                }
            }
        }

        /// <summary>
        /// 设置插入的图品数据
        /// </summary>
        /// <param name="picpaths"></param>
        public void SetNodePic(Dictionary<string, WordPic> picpaths)
        {
            XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
            //XmlNodeList nodeList = xdoc.SelectNodes("//w:bookmarkStart", nsmgr);
            foreach (XmlNode node in nodeList)
            {
                SetBookMarkPics(xdoc, node, picpaths);
            }
        }

        /// <summary>
        /// 保存导出的数据
        /// </summary>
        /// <param name="docPath"></param>
        public void Save(string docPath)
        {
            xdoc.Save(docPath);
        }

        #endregion

        #region 导出word文档内部方法

        /// <summary>
        /// 根据标签插入对应的值
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="bookmarks"></param>
        private void SetBookMarkTexts(XmlDocument xdoc, XmlNode node, Dictionary<string, string> bookmarks)
        {
            //找到bookmark结束标记
            if (node.NextSibling.Name.ToString() == "aml:annotation")
            {
                //查找bookmarks中是否在word标签
                if (bookmarks.ContainsKey(node.Attributes["w:name"].Value))
                {
                    //得到node上一个兄弟节点style ("w:rPr")的克隆,以备添给新加内容,样式继承
                    XmlNode nodeStyle = null;
                    if (node.PreviousSibling != null)
                        nodeStyle = node.PreviousSibling.CloneNode(true);
                    else
                        nodeStyle = node.ParentNode.SelectNodes("//w:r", nsmgr)[0].CloneNode(true);
                    //父节点 "w:p"
                    XmlNode bookmrkParent = node.ParentNode;
                    XmlElement tagRun;
                    tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
                    bookmrkParent.AppendChild(tagRun);
                    //添加样式
                    if (nodeStyle.SelectSingleNode("//w:rPr", nsmgr) != null)
                        tagRun.AppendChild(nodeStyle.SelectSingleNode("//w:rPr", nsmgr));
                    XmlElement tagText;
                    tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
                    tagRun.AppendChild(tagText);
                    //插入(w:t)文本作为内容,追加至文本节点

                    if (bookmarks[node.Attributes["w:name"].Value] == null)
                        return;
                    XmlNode nodeText;
                    nodeText = xdoc.CreateNode(XmlNodeType.Text, "w:t", nsmgr.LookupNamespace("w"));
                    nodeText.Value = bookmarks[node.Attributes["w:name"].Value].ToString();
                    tagText.AppendChild(nodeText);
                }
            }
        }

        /// <summary>
        /// 根据标签水平插入一张表数据,即列名在数据上侧
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="wordtables"></param>
        private void SetBookMarkTablesHorizontal(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
        {
            if (node.NextSibling.Name.ToString() == "aml:annotation")
            {
                //查找bookmarks中是否在word标签
                if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
                {
                    // "w:p"节点的父节点
                    XmlNode bookmrkParent = node.ParentNode;
                    XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
                    XmlElement tagtable;
                    tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
                    bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

                    SetImportTableBorder(ref xdoc, ref tagtable);

                    XmlElement tagtr;
                    tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                    tagtable.AppendChild(tagtr);

                    foreach (string headstr in wordtables[node.Attributes["w:name"].Value].TableHeads)
                    {
                        SetTableTitle(ref tagtr, headstr);
                    }

                    for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
                    {
                        tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                        tagtable.AppendChild(tagtr);

                        for (int j = 0; j < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1); j++)
                        {
                            string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
                            SetTableContent(ref tagtr, content);

                        }
                    }
                }
            }
        }

        /// <summary>
        /// 根据标签垂直插入一张表数据,即列名在数据左侧
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="wordtables"></param>
        private void SetBookMarkTablesVertical(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
        {
            if (node.NextSibling.Name.ToString() == "aml:annotation")
            {
                //查找bookmarks中是否在word标签
                if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
                {
                    // "w:p"节点的父节点
                    XmlNode bookmrkParent = node.ParentNode;
                    XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
                    XmlElement tagtable;
                    tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
                    bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

                    //设置表格样式
                    SetImportTableBorder(ref xdoc, ref tagtable);

                    for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
                    {
                        for (int j = 0; j < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1); j++)
                        {
                            XmlElement tagtr;
                            tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                            tagtable.AppendChild(tagtr);
                            if (wordtables[node.Attributes["w:name"].Value].TableHeads[j] == null)
                                return;
                            string headstr = wordtables[node.Attributes["w:name"].Value].TableHeads[j];
                            SetTableTitle(ref tagtr, headstr);
                            if (wordtables[node.Attributes["w:name"].Value].TableValues[i, j] == null)
                                return;
                            string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
                            SetTableContent(ref tagtr, content);

                        }

                    }
                }
            }
        }

        /// <summary>
        /// 根据标签水平插入一张表数据,即列名在数据上侧
        /// 表中最后一列为图片的地址
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="wordtables"></param> 
        private void SetBookMarkTablesPictureHorizontal(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
        {
            if (node.NextSibling.Name.ToString() == "aml:annotation")
            {
                //查找bookmarks中是否在word标签
                if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
                {
                    // "w:p"节点的父节点
                    XmlNode bookmrkParent = node.ParentNode;
                    XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
                    XmlElement tagtable;
                    tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
                    bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

                    SetImportTableBorder(ref xdoc, ref tagtable);

                    XmlElement tagtr;
                    tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                    tagtable.AppendChild(tagtr);

                    //循环输入列名,最后一行跳过,最后一行为图片的地址
                    for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableHeads.Length - 1; i++)
                    {
                        string headstr = wordtables[node.Attributes["w:name"].Value].TableHeads[i];
                        SetTableTitle(ref tagtr, headstr);
                    }


                    for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
                    {
                        tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                        tagtable.AppendChild(tagtr);

                        int colLength = wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1);

                        for (int j = 0; j < colLength - 1; j++)
                        {
                            string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
                            SetTableContent(ref tagtr, content);
                        }
                        tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                        tagtable.AppendChild(tagtr);
                        SetTablePicture(ref tagtr, wordtables[node.Attributes["w:name"].Value].TableValues[i, colLength - 1], (colLength - 1).ToString());
                    }
                }
            }
        }

        /// <summary>
        /// 根据标签垂直插入一张表数据,即列名在数据左侧
        /// 表中最后一列为图片的地址
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="wordtables"></param>
        private void SetBookMarkTablesPictureVertical(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
        {
            if (node.NextSibling.Name.ToString() == "aml:annotation")
            {
                //查找bookmarks中是否在word标签
                if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
                {
                    // "w:p"节点的父节点
                    XmlNode bookmrkParent = node.ParentNode;
                    XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
                    XmlElement tagtable;
                    tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
                    bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

                    //设置表格样式
                    SetImportTableBorder(ref xdoc, ref tagtable);

                    for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
                    {
                        int colLength = wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1);
                        XmlElement tagtr;
                        for (int j = 0; j < colLength - 1; j++)
                        {

                            tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                            tagtable.AppendChild(tagtr);
                            string headstr = wordtables[node.Attributes["w:name"].Value].TableHeads[j];
                            SetTableTitle(ref tagtr, headstr);
                            string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
                            SetTableContent(ref tagtr, content);
                        }
                        tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
                        tagtable.AppendChild(tagtr);
                        SetTablePicture(ref tagtr, wordtables[node.Attributes["w:name"].Value].TableValues[i, colLength - 1]);
                    }
                }
            }
        }

        /// <summary>
        /// 设置列名
        /// </summary>
        private void SetTableTitle(ref XmlElement tagtr, string headstr)
        {
            XmlElement tagtc;
            tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
            tagtr.AppendChild(tagtc);

            XmlElement tagP;
            tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
            tagtc.AppendChild(tagP);

            XmlElement tagRun;
            tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
            tagP.AppendChild(tagRun);

            //加粗<w:rPr><w:b/></w:rPr>
            //设置字体为<w:rPr><w:rFonts w:hint="fareast"/></w:rPr>
            XmlElement tagPr;
            tagPr = xdoc.CreateElement("w:rPr", nsmgr.LookupNamespace("w"));
            tagRun.AppendChild(tagPr);

            XmlElement tagB;
            tagB = xdoc.CreateElement("w:b", nsmgr.LookupNamespace("w"));
            tagPr.AppendChild(tagB);

            XmlElement tagText;
            tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
            tagRun.AppendChild(tagText);
            //插入(w:t)文本作为内容,追加至文本节点
            XmlNode nodeText;
            nodeText = xdoc.CreateNode(XmlNodeType.Text, "w:t", nsmgr.LookupNamespace("w"));
            nodeText.Value = headstr;
            tagText.AppendChild(nodeText);
        }

        /// <summary>
        /// 设置表的内容
        /// </summary>
        private void SetTableContent(ref XmlElement tagtr, string content)
        {
            XmlElement tagtc;
            tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
            tagtr.AppendChild(tagtc);

            XmlElement tagP;
            tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
            tagtc.AppendChild(tagP);

            XmlElement tagRun;
            tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
            tagP.AppendChild(tagRun);

            XmlElement tagText;
            tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
            tagRun.AppendChild(tagText);

            //插入(w:t)文本作为内容,追加至文本节点
            XmlNode nodeText;
            nodeText = xdoc.CreateNode(XmlNodeType.Text, "w:t", nsmgr.LookupNamespace("w"));
            nodeText.Value = content;
            tagText.AppendChild(nodeText);
        }

        /// <summary>
        /// 设置表中图片
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="Path">Path</param>
        private void SetTablePicture(ref XmlElement tagtr, string path)
        {
            Bitmap bitmap = new Bitmap(path);

            XmlElement tagtc;
            tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
            tagtr.AppendChild(tagtc);

            XmlElement tagP;
            tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
            tagtc.AppendChild(tagP);

            XmlElement tagRun;
            tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
            tagP.AppendChild(tagRun);

            XmlElement tagText;
            tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
            tagRun.AppendChild(tagText);

            XmlElement tagPic;
            tagPic = xdoc.CreateElement("w:pict", nsmgr.LookupNamespace("w"));
            tagRun.AppendChild(tagPic);

            XmlElement tagbindData;
            tagbindData = xdoc.CreateElement("w:binData", nsmgr.LookupNamespace("w"));
            tagPic.AppendChild(tagbindData);

            XmlAttribute nodeAttr;
            nodeAttr = xdoc.CreateAttribute("w:name", nsmgr.LookupNamespace("w"));
            nodeAttr.Value = "wordml://" + Path.GetFileName(path);
            tagbindData.Attributes.Append(nodeAttr);

            //xml:space="preserve"
            nodeAttr = xdoc.CreateAttribute("xml:space");
            nodeAttr.Value = "preserve";
            tagbindData.Attributes.Append(nodeAttr);

            XmlNode nodePicValue;
            nodePicValue = xdoc.CreateNode(XmlNodeType.Text, "w:binData", nsmgr.LookupNamespace("w"));
            nodePicValue.Value = ImgToBase64String(path);
            tagbindData.AppendChild(nodePicValue);

            XmlElement tagShape;
            tagShape = xdoc.CreateElement("v:shape", nsmgr.LookupNamespace("v"));
            tagPic.AppendChild(tagShape);

            XmlAttribute tagStyle;
            tagStyle = xdoc.CreateAttribute("style");
            tagStyle.Value = "width:" + WordWidth + "pt;height:" + WordHeight + "pt;";
            tagShape.Attributes.Append(tagStyle);


            XmlElement tagimagedata;
            tagimagedata = xdoc.CreateElement("v:imagedata", nsmgr.LookupNamespace("v"));
            tagShape.AppendChild(tagimagedata);

            nodeAttr = xdoc.CreateAttribute("src");
            nodeAttr.Value = "wordml://" + Path.GetFileName(path);
            tagimagedata.Attributes.Append(nodeAttr);


        }

        /// <summary>
        /// 设置表中图片
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="Path">Path</param>
        /// <param name="colNum">合并的列数</param>
        private void SetTablePicture(ref XmlElement tagtr, string path, string colNum)
        {
            Bitmap bitmap = new Bitmap(path);

            XmlElement tagtc;
            tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
            tagtr.AppendChild(tagtc);

            if (colNum != string.Empty)
            {
                XmlElement tagtcPr;
                tagtcPr = xdoc.CreateElement("w:tcPr", nsmgr.LookupNamespace("w"));
                tagtc.AppendChild(tagtcPr);

                XmlElement tagtcW;
                tagtcW = xdoc.CreateElement("w:tcW", nsmgr.LookupNamespace("w"));
                tagtcPr.AppendChild(tagtcW);

                XmlAttribute nodew;
                nodew = xdoc.CreateAttribute("w:w", nsmgr.LookupNamespace("w"));
                nodew.Value = "0";
                tagtcW.Attributes.Append(nodew);

                XmlAttribute nodetype;
                nodetype = xdoc.CreateAttribute("w:type", nsmgr.LookupNamespace("w"));
                nodetype.Value = "auto";
                tagtcW.Attributes.Append(nodetype);

                XmlElement taggridSpan;
                taggridSpan = xdoc.CreateElement("w:gridSpan", nsmgr.LookupNamespace("w"));
                tagtcPr.AppendChild(taggridSpan);

                XmlAttribute nodegridSpan;
                nodegridSpan = xdoc.CreateAttribute("w:val", nsmgr.LookupNamespace("w"));
                nodegridSpan.Value = colNum;
                taggridSpan.Attributes.Append(nodegridSpan);
            }

            XmlElement tagP;
            tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
            tagtc.AppendChild(tagP);

            XmlElement tagRun;
            tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
            tagP.AppendChild(tagRun);

            XmlElement tagText;
            tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
            tagRun.AppendChild(tagText);

            XmlElement tagPic;
            tagPic = xdoc.CreateElement("w:pict", nsmgr.LookupNamespace("w"));
            tagRun.AppendChild(tagPic);

            XmlElement tagbindData;
            tagbindData = xdoc.CreateElement("w:binData", nsmgr.LookupNamespace("w"));
            tagPic.AppendChild(tagbindData);

            XmlAttribute nodeAttr;
            nodeAttr = xdoc.CreateAttribute("w:name", nsmgr.LookupNamespace("w"));
            nodeAttr.Value = "wordml://" + Path.GetFileName(path);
            tagbindData.Attributes.Append(nodeAttr);

            //xml:space="preserve"
            nodeAttr = xdoc.CreateAttribute("xml:space");
            nodeAttr.Value = "preserve";
            tagbindData.Attributes.Append(nodeAttr);

            XmlNode nodePicValue;
            nodePicValue = xdoc.CreateNode(XmlNodeType.Text, "w:binData", nsmgr.LookupNamespace("w"));
            nodePicValue.Value = ImgToBase64String(path);
            tagbindData.AppendChild(nodePicValue);

            XmlElement tagShape;
            tagShape = xdoc.CreateElement("v:shape", nsmgr.LookupNamespace("v"));
            tagPic.AppendChild(tagShape);

            XmlAttribute tagStyle;
            tagStyle = xdoc.CreateAttribute("style");
            tagStyle.Value = "width:" + WordWidth + "pt;height:" + WordHeight + "pt;";
            tagShape.Attributes.Append(tagStyle);


            XmlElement tagimagedata;
            tagimagedata = xdoc.CreateElement("v:imagedata", nsmgr.LookupNamespace("v"));
            tagShape.AppendChild(tagimagedata);

            nodeAttr = xdoc.CreateAttribute("src");
            nodeAttr.Value = "wordml://" + Path.GetFileName(path);
            tagimagedata.Attributes.Append(nodeAttr);


        }

        /// <summary>
        /// 设置导出表的边框样式
        /// </summary>
        /// <param name="xdoc"></param>
        private void SetImportTableBorder(ref XmlDocument xdoc, ref XmlElement tagtable)
        {

            XmlElement tagborder;
            tagborder = xdoc.CreateElement("w:tblBorders", nsmgr.LookupNamespace("w"));
            tagtable.AppendChild(tagborder);

            XmlElement tagtop;
            tagtop = xdoc.CreateElement("w:top", nsmgr.LookupNamespace("w"));
            tagborder.AppendChild(tagtop);

            XmlAttribute borderValAtrr;
            borderValAtrr = xdoc.CreateAttribute("w:val", nsmgr.LookupNamespace("w"));
            borderValAtrr.Value = "single";
            tagtop.Attributes.Append(borderValAtrr);

            XmlAttribute borderSzAtrr;
            borderSzAtrr = xdoc.CreateAttribute("w:sz", nsmgr.LookupNamespace("w"));
            borderSzAtrr.Value = "4";
            tagtop.Attributes.Append(borderSzAtrr);

            XmlAttribute borderwidthAtrr;
            borderwidthAtrr = xdoc.CreateAttribute("wx:bdrwidth", nsmgr.LookupNamespace("wx"));
            borderwidthAtrr.Value = "10";
            tagtop.Attributes.Append(borderwidthAtrr);

            XmlAttribute borderspaceAtrr;
            borderspaceAtrr = xdoc.CreateAttribute("w:space", nsmgr.LookupNamespace("w"));
            borderspaceAtrr.Value = "0";
            tagtop.Attributes.Append(borderspaceAtrr);

            XmlAttribute bordercolorAtrr;
            bordercolorAtrr = xdoc.CreateAttribute("w:color", nsmgr.LookupNamespace("w"));
            bordercolorAtrr.Value = "auto";
            tagtop.Attributes.Append(bordercolorAtrr);

            XmlElement tagleft;
            tagleft = xdoc.CreateElement("w:left", nsmgr.LookupNamespace("w"));
            tagborder.AppendChild(tagleft);
            tagleft.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
            tagleft.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
            tagleft.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
            tagleft.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
            tagleft.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

            XmlElement tagbottom;
            tagbottom = xdoc.CreateElement("w:bottom", nsmgr.LookupNamespace("w"));
            tagborder.AppendChild(tagbottom);
            tagbottom.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
            tagbottom.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
            tagbottom.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
            tagbottom.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
            tagbottom.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

            XmlElement tagright;
            tagright = xdoc.CreateElement("w:right", nsmgr.LookupNamespace("w"));
            tagborder.AppendChild(tagright);
            tagright.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
            tagright.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
            tagright.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
            tagright.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
            tagright.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

            XmlElement taginsideH;
            taginsideH = xdoc.CreateElement("w:insideH", nsmgr.LookupNamespace("w"));
            tagborder.AppendChild(taginsideH);
            taginsideH.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
            taginsideH.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
            taginsideH.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
            taginsideH.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
            taginsideH.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

            XmlElement taginsideV;
            taginsideV = xdoc.CreateElement("w:insideV", nsmgr.LookupNamespace("w"));
            tagborder.AppendChild(taginsideV);
            taginsideV.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
            taginsideV.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
            taginsideV.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
            taginsideV.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
            taginsideV.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

        }

        /// <summary>
        /// 根据标签插入一张图片
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="picpaths"></param>
        private void SetBookMarkPics(XmlDocument xdoc, XmlNode node, Dictionary<string, WordPic> picpaths)
        {
            if (node.NextSibling.Name.ToString() == "aml:annotation")//w:bookmarkEnd
            {
                //查找bookmarks中是否在word标签
                if (picpaths.ContainsKey(node.Attributes["w:name"].Value))
                {
                    // "w:p"节点的父节点
                    XmlNode bookmrkParent = node.ParentNode;
                    XmlNode bookmrkParentParent = node.ParentNode.ParentNode;

                    XmlElement tagPic;
                    tagPic = xdoc.CreateElement("w:pict", nsmgr.LookupNamespace("w"));
                    bookmrkParent.InsertAfter(tagPic, node);

                    XmlElement tagbindData;
                    tagbindData = xdoc.CreateElement("w:binData", nsmgr.LookupNamespace("w"));
                    tagPic.AppendChild(tagbindData);

                    XmlAttribute nodeAttr;
                    nodeAttr = xdoc.CreateAttribute("w:name", nsmgr.LookupNamespace("w"));
                    nodeAttr.Value = "wordml://" + Path.GetFileName(picpaths[node.Attributes["w:name"].Value].PicPath);
                    tagbindData.Attributes.Append(nodeAttr);

                    //xml:space="preserve"
                    nodeAttr = xdoc.CreateAttribute("xml:space");
                    nodeAttr.Value = "preserve";
                    tagbindData.Attributes.Append(nodeAttr);


                    XmlNode nodePicValue;
                    nodePicValue = xdoc.CreateNode(XmlNodeType.Text, "w:binData", nsmgr.LookupNamespace("w"));
                    nodePicValue.Value = ImgToBase64String(picpaths[node.Attributes["w:name"].Value].PicPath);
                    tagbindData.AppendChild(nodePicValue);

                    XmlElement tagShape;
                    tagShape = xdoc.CreateElement("v:shape", nsmgr.LookupNamespace("v"));
                    tagPic.AppendChild(tagShape);


                    XmlAttribute tagStyle;
                    tagStyle = xdoc.CreateAttribute("style");
                    tagStyle.Value = "width:" + picpaths[node.Attributes["w:name"].Value].Width + "pt;height:" + picpaths[node.Attributes["w:name"].Value].Height + "pt;";
                    tagShape.Attributes.Append(tagStyle);


                    XmlElement tagimagedata;
                    tagimagedata = xdoc.CreateElement("v:imagedata", nsmgr.LookupNamespace("v"));
                    tagShape.AppendChild(tagimagedata);

                    nodeAttr = xdoc.CreateAttribute("src");
                    nodeAttr.Value = "wordml://" + Path.GetFileName(picpaths[node.Attributes["w:name"].Value].PicPath);
                    tagimagedata.Attributes.Append(nodeAttr);

                }
            }
        }

        private string ImgToBase64String(string Imagefilename)
        {
            System.IO.MemoryStream m = new System.IO.MemoryStream();
            try
            {
                System.Drawing.Bitmap bp = new System.Drawing.Bitmap(Imagefilename);
                bp.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] b = m.GetBuffer();
                return Convert.ToBase64String(b);
            }
            finally
            {
                m.Close();
            }
        }

        #endregion

        #region Rubish

        //private static void CreateHtmlChunks(Package package, Dictionary<string, string> bookmarks)
        //{
        //    Package pkgOutputDoc = package;

        //    Uri uriBase = new Uri("/word/document.xml", UriKind.Relative);
        //    PackagePart partDocumentXML = pkgOutputDoc.GetPart(uriBase);

        //    foreach (string key in bookmarks.Keys)
        //    {
        //        Uri uri = new Uri("/word/" + key + ".html", UriKind.Relative);
        //        string html = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><html><head><title></title></head><body>"
        //            + bookmarks[key].ToString()
        //            + "</body></html>";
        //        byte[] Origem = Encoding.UTF8.GetBytes(html);
        //        PackagePart altChunkpart = pkgOutputDoc.CreatePart(uri, "text/html");
        //        using (Stream targetStream = altChunkpart.GetStream())
        //        {
        //            targetStream.Write(Origem, 0, Origem.Length);
        //        }
        //        Uri relativeAltUri =
        //        PackUriHelper.GetRelativeUri(uriBase, uri);

        //        partDocumentXML.CreateRelationship(relativeAltUri, TargetMode.Internal,
        //            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk",
        //            key);
        //    }

        //    pkgOutputDoc.Flush();
        //}

        #endregion

        #region

        //WordTable对象
        public class WordTable
        {

            private string[] _tableHeads;

            public string[] TableHeads
            {
                get { return _tableHeads; }
                set { _tableHeads = value; }
            }

            private string[,] _tableValues;

            public string[,] TableValues
            {
                get { return _tableValues; }
                set { _tableValues = value; }
            }

            public static WordTable GetWordTabelFromDataTable(System.Data.DataTable table)
            {

                WordTable wordtable = new WordTable();
                if (table != null)
                {
                    string[] tableheads = new string[table.Columns.Count];
                    int i = 0;
                    foreach (DataColumn dc in table.Columns)
                    {
                        tableheads[i] = dc.ColumnName;
                        i++;
                    }
                    wordtable.TableHeads = tableheads;

                    i = 0;
                    string[,] tablevalues = new string[table.Rows.Count, table.Columns.Count];
                    for (int j = 0; j < table.Rows.Count; j++)
                    {
                        for (int k = 0; k < table.Columns.Count; k++)
                        {
                            tablevalues[j, k] = table.Rows[j][k].ToString();
                        }
                    }
                    wordtable.TableValues = tablevalues;
                }
                return wordtable;
            }
        }

        //word中插入的图片对象
        public class WordPic
        {
            private int _height;

            public int Height
            {
                get { return _height; }
                set { _height = value; }
            }

            private int _width;

            public int Width
            {
                get { return _width; }
                set { _width = value; }
            }

            private string _picpath;

            public string PicPath
            {
                get { return _picpath; }
                set { _picpath = value; }
            }
        }

        #endregion
        /// <summary>
        /// 合并XML文档,将strCopyFolder中的XML文档合并到path1中
        /// </summary>
        public string MergeXML(string path1, string strCopyFolder, string savepath)
        {
            XmlDocument doc1 = new XmlDocument();
            XmlDocument doc2 = new XmlDocument();
            doc1.Load(path1);
            nsmgr = new XmlNamespaceManager(doc1.NameTable);
            nsmgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");
            XmlNodeList nodeList1 = doc1.SelectNodes("//w:body", nsmgr);
            XmlNode node1_body;

            string[] arrFiles = Directory.GetFiles(strCopyFolder);

            node1_body = nodeList1.Item(0);
            foreach (string strFile in arrFiles)
            {
                doc2.Load(strFile);
                foreach (XmlNode n in doc2.SelectSingleNode("//w:body", nsmgr).ChildNodes)
                {
                    XmlNode node2 = doc1.ImportNode(n, true);
                    node1_body.AppendChild(node2);
                }
            }
            doc1.Save(savepath);
            return savepath;
        }
    }
}

后台代码:

 

            ExportWordML expwordml = new ExportWordML();
            expwordml.CreateXmlDom(Server.MapPath("~/Template/人员档案表.xml"));
            Dictionary<string, string> wordTexts = new Dictionary<string, string>();
            Dictionary<string, Utility.ExportWordML.WordPic> dic_wordpic = new Dictionary<string, ExportWordML.WordPic>();
	    wordTexts.Add("user_name" + i, "张三");
            wordTexts.Add("sex" + i, "男");
	    expwordml.SetNodeText(wordTexts);
            Utility.ExportWordML.WordPic portrait_pic = new ExportWordML.WordPic();
            portrait_pic.Width = 85;
            portrait_pic.Height = 90;
            portrait_pic.PicPath = Server.MapPath(picturePath);
            dic_wordpic.Add("Portrait_url", portrait_pic);
	    expwordml.SetNodePic(dic_wordpic);
	    expwordml.Save(Server.MapPath("~/Template/EntryfileTemp/员工档案.doc"); 

 

 

 

 

 

 

插入图片后导出的文档使用word打开时,报了格式错误,于是对类中的插入图片方法做了下修改

 

        /// <summary>
        /// 根据标签插入一张图片
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="node"></param>
        /// <param name="picpaths"></param>
        private void SetBookMarkPics(XmlDocument xdoc, XmlNode node, Dictionary<string, WordPic> picpaths)
        {
            if (node.NextSibling.Name.ToString() == "aml:annotation")//w:bookmarkEnd
            {
                //查找bookmarks中是否在word标签
                if (picpaths.ContainsKey(node.Attributes["w:name"].Value))
                {
                    // "w:p"节点的父节点
                    XmlNode bookmrkParent = node.ParentNode;
                    XmlNode bookmrkParentParent = node.ParentNode.ParentNode;

                    XmlElement tagPic;
                    tagPic = xdoc.CreateElement("w:pict", nsmgr.LookupNamespace("w"));
                    bookmrkParent.InsertAfter(tagPic, node);//原为 bookmrkParentParent.InsertAfter(tagPic, bookmrkParent);

                    XmlElement tagbindData;
                    tagbindData = xdoc.CreateElement("w:binData", nsmgr.LookupNamespace("w"));
                    tagPic.AppendChild(tagbindData);

                    XmlAttribute nodeAttr;
                    nodeAttr = xdoc.CreateAttribute("w:name", nsmgr.LookupNamespace("w"));
                    nodeAttr.Value = "wordml://" + Path.GetFileName(picpaths[node.Attributes["w:name"].Value].PicPath);
                    tagbindData.Attributes.Append(nodeAttr);

                    //xml:space="preserve"
                    nodeAttr = xdoc.CreateAttribute("xml:space");
                    nodeAttr.Value = "preserve";
                    tagbindData.Attributes.Append(nodeAttr);


                    XmlNode nodePicValue;
                    nodePicValue = xdoc.CreateNode(XmlNodeType.Text, "w:binData", nsmgr.LookupNamespace("w"));
                    nodePicValue.Value = ImgToBase64String(picpaths[node.Attributes["w:name"].Value].PicPath);
                    tagbindData.AppendChild(nodePicValue);

                    XmlElement tagShape;
                    tagShape = xdoc.CreateElement("v:shape", nsmgr.LookupNamespace("v"));
                    tagPic.AppendChild(tagShape);


                    XmlAttribute tagStyle;
                    tagStyle = xdoc.CreateAttribute("style");
                    tagStyle.Value = "width:" + picpaths[node.Attributes["w:name"].Value].Width + "pt;height:" + picpaths[node.Attributes["w:name"].Value].Height + "pt;";
                    tagShape.Attributes.Append(tagStyle);


                    XmlElement tagimagedata;
                    tagimagedata = xdoc.CreateElement("v:imagedata", nsmgr.LookupNamespace("v"));
                    tagShape.AppendChild(tagimagedata);

                    nodeAttr = xdoc.CreateAttribute("src");
                    nodeAttr.Value = "wordml://" + Path.GetFileName(picpaths[node.Attributes["w:name"].Value].PicPath);
                    tagimagedata.Attributes.Append(nodeAttr);

                }
            }
        }

 

 

 


另附合并xml文档的方法

 

 

 

        /// <summary>
        /// 合并XML文档,将strCopyFolder中的XML文档合并到path1中
        /// </summary>
        public string MergeXML(string path1, string strCopyFolder, string savepath)
        {
            XmlDocument doc1 = new XmlDocument();
            XmlDocument doc2 = new XmlDocument();
            doc1.Load(path1);
            nsmgr = new XmlNamespaceManager(doc1.NameTable);
            nsmgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");
            XmlNodeList nodeList1 = doc1.SelectNodes("//w:body", nsmgr);
            XmlNode node1_body;

            string[] arrFiles = Directory.GetFiles(strCopyFolder);

            node1_body = nodeList1.Item(0);
            foreach (string strFile in arrFiles)
            {
                doc2.Load(strFile);
                foreach (XmlNode n in doc2.SelectSingleNode("//w:body", nsmgr).ChildNodes)
                {
                    XmlNode node2 = doc1.ImportNode(n, true);
                    node1_body.AppendChild(node2);
                }
            }
            doc1.Save(savepath);
            return savepath;
        }

 

 

 

 

 

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据的流

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值