OpenXml开发-在书签处插入内容

///


        /// 通过书签定位
        ///

        /// 原始文档
        /// 对应的书签名
        ///
        ///
        /// 通过已经在文档中定义的书签名称定位到xml中指定的节点位置,返回对应书签节点的
        /// 父节点XmlWriter对象,这里的参数overwrite表示是否需要覆盖当前书签节点所在的父节点。因为一般
        /// 书签都是定义在一个段落的标记中的,而当需要插入表格或者图片的时候,如果直接插入到段落标记中
        /// 是不合法的,所以需要覆盖掉当前的段落标记,这个时候只要设置overwrite=true就行了。
        ///

        public static XmlWriter GetXmlWriterByBookMark(XmlDocument documentXml,string bookMark,bool overwrite)
        {
            try
            {
                XPathNavigator xNav = XmlHelper.SelectElement(documentXml, String.Format("//w:bookmarkStart[@w:name=""{0}""]", bookMark), Namespaces.NamespaceManager);
                xNav.MoveToParent();
                XmlWriter writer;
                if (!overwrite) writer = xNav.AppendChild();// (xNav);
                else writer = xNav.ReplaceRange(xNav);
                return writer;
            }
            catch { return null; }
        }

调用:
        PackageHelper package;
            WordprocessingDoc xmlDoc = new WordprocessingDoc("CellReportTemplate4C.docx");
            package = xmlDoc.Package;
            Uri documentUri =
             new Uri(@"/word/document.xml", UriKind.Relative);
            XmlDocument documentXml =
                package.GetWritablePart(documentUri);

            WordProcessing.AppendStyle(xmlDoc);

           using (XmlWriter writer = WordprocessingDoc.GetXmlWriterByBookMark(documentXml, "时间",false))
            {
                xmlDoc.WriteText(writer, CurrentStartTime.ToShortDateString() + "到" + CurrentEndTime.ToShortDateString());
            }

        using (XmlWriter writer = WordprocessingDoc.GetXmlWriterByBookMark(documentXml, "表格", true))
            {
                dtTemp = GetTextTable();
                if (dtTemp != null) xmlDoc.RenderTableH(writer, dtTemp, "MyTableStyle2");
            }

转载于:https://www.cnblogs.com/hjzhang/archive/2009/12/04/2043574.html

你可能感兴趣的:(OpenXml开发-在书签处插入内容)