word2007 模板替换代码:

word2007 模板替换代码:

private   void   btnGenerateFinance_Click( object   sender,   RibbonControlEventArgs   e)
        {
              try
            {
                  string   thisdocFullPath =   Globals .ThisAddIn.Application.ActiveDocument.FullName;
                  if   ( String .IsNullOrEmpty(thisdocFullPath) || !System.IO. File .Exists(thisdocFullPath))
                {
                      MessageBox .Show( "Please save current document firstly" ,   "Waring" , MessageBoxButtons .OK,   MessageBoxIcon .Warning);
                      return ;
                }
                  FrmWait .BeginWait();

                  string   customXML =   @" " ;
                  //MessageBox.Show(customXML);

                  object   template = thisdocFullPath;
                  object   newTemplate =   false ;
                  object   documentType = 0;
                  object   visible = System. Type .Missing;
                  Document   sampledoc =   Globals .ThisAddIn.Application.Documents.Add( ref   template,   ref newTemplate,   ref   documentType,   ref   visible);
                  object   missing = System. Type .Missing;
                  object   savePath =   Environment .GetEnvironmentVariable( "temp" ) +   "//"   + sampledoc.FullName +   ".docx" ;
                sampledoc.SaveAs( ref   savePath,   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,
                      ref   missing);
                sampledoc.ActiveWindow.Close( ref   missing,   ref   missing);
                  using   ( WordprocessingDocument   wordDoc = WordprocessingDocument .Open(savePath.ToString(),   true ))
                {
                      MainDocumentPart   mainPart = wordDoc.MainDocumentPart;

                    #region   handle repeat items
                      XmlDocument   customDoc =   new   XmlDocument ();
                    customDoc.LoadXml(customXML);

                      XmlDocument   doc =   new   XmlDocument ();
                    doc.LoadXml(mainPart.Document.Body.OuterXml);
                      XmlNodeList   groupList1 = doc.GetElementsByTagName( "w:group" );

                      List < XmlNode > groupList =   new   List < XmlNode >();
                      foreach   ( XmlNode   node   in   groupList1)
                    {
                        groupList.Add(node);
                    }
                      List < XmlNode > removeList =   new   List < XmlNode >();

                      int   repeatCount = 0;
                      foreach   ( XmlNode   node   in   groupList)
                    {
                        repeatCount = GetGroupRepeatCount(node.ParentNode.ParentNode.OuterXml, customDoc);
                          if   (repeatCount > 0)
                        {
                              XmlNode   groupNodeTemplate = node.ParentNode.ParentNode.CloneNode( true );
                              XmlNode   beforeNode = node.ParentNode.ParentNode;

                              //for (int i = 1; i <= repeatCount; i++)
                              for   ( int   i = repeatCount; i >= 1; i--)
                            {
                                  XmlNode   newNode = groupNodeTemplate.CloneNode( true );
                                  //ModifyRepeatGroup(ref newNode, i, customDoc);
                                GenerateRepeatGroup( ref   newNode, i, customDoc);
                                beforeNode.ParentNode.InsertAfter(newNode, beforeNode);
                            }
                            removeList.Add(beforeNode);
                        }
                    }
                      foreach   ( XmlNode   node   in   removeList)
                    {
                        node.ParentNode.RemoveChild(node);
                    }
                    mainPart.Document.Body.InnerXml = doc.InnerXml;

                    mainPart.Document.Save();
                    #endregion

                    mainPart.DeleteParts< CustomXmlPart >(mainPart.CustomXmlParts);

                      //Add a new customXML part and then add content
                      //CustomXmlPart customXmlPart = mainPart.AddNewPart<CustomXmlPart>();
                      CustomXmlPart   customXmlPart = mainPart.AddCustomXmlPart( CustomXmlPartType .CustomXml);

                      //copy the XML into the new part...
                      using   ( StreamWriter   ts =   new   StreamWriter (customXmlPart.GetStream()))
                        ts.Write(customXML);
                }

                  //sampledoc.Activate();
                sampledoc =   Globals .ThisAddIn.Application.Documents.Open( ref   savePath,   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,
                      ref   missing);

                  FrmWait .EndWait();
                sampledoc.Activate();
            }
              catch   ( Exception   ex)
            {
                  FrmWait .EndWait();
                  MessageBox .Show(ex.Message,   "Error" ,   MessageBoxButtons .OK,   MessageBoxIcon .Error);
            }
        }
          private   int   GetGroupRepeatCount( string   groupXml,   XmlDocument   customXmlDoc)
        {
            groupDoc.LoadXml(groupXml);
              XmlNodeList   dataList = groupDoc.GetElementsByTagName( "w:dataBinding" );
              int   maxRepeat = 0, nodeCount;
              string   path =   "" ;

              foreach   ( XmlNode   node   in   dataList)
            {
                path = node.Attributes[ "w:xpath" ].Value;
                  //customXmlDoc.SelectNodes(path).Item(0)
                  int   index;
                  foreach   ( XmlNode   xn   in   customXmlDoc.SelectNodes(path))
                {
                      for   ( int   i = 0; i < xn.ParentNode.ChildNodes.Count; i++)
                    {
                          if   (xn.ParentNode.ChildNodes[i].Equals(xn))
                        {
                            index = i;
                              break ;
                        }
                    }
                }


                nodeCount = customXmlDoc.SelectNodes(path).Count;
                  if   (nodeCount > maxRepeat)
                    maxRepeat = nodeCount;
            }

              return   maxRepeat;
        }
          private   void   GenerateRepeatGroup( ref   XmlNode   groupNode,   int   repeatIndex,   XmlDocument customXmlDoc)
        {
            groupDoc.LoadXml(groupNode.OuterXml);
              //w:id value must unique
              XmlNodeList   idList = groupDoc.GetElementsByTagName( "w:id" );
              string   idValue;
              foreach   ( XmlNode   node   in   idList)
            {
                idValue = node.Attributes[ "w:val" ].Value;
                node.Attributes[ "w:val" ].Value = idValue + repeatIndex.ToString();
            }

              XmlNodeList   dataList = groupDoc.GetElementsByTagName( "w:dataBinding" );
              string   pathValue;
              //modify xpath e.g /Customer/Item[1]/Title
              foreach   ( XmlNode   node   in   dataList)
            {
                pathValue = node.Attributes[ "w:xpath" ].Value;
                  XmlNodeList   dataNodeList = customXmlDoc.SelectNodes(pathValue);
                  int   dataNodeCount = dataNodeList.Count;
                  //if this group contain not repeat data, then don't to change xpaht value
                  if   (dataNodeCount > 1 && repeatIndex <= dataNodeCount)
                {
                      //pathValue = pathValue.Insert(pathValue.LastIndexOf("/"), "[" + repeatIndex.ToString() + "]");
                      List < int > pathIndexList =   new   List < int >();
                    CheckNodeIndex(dataNodeList[repeatIndex - 1],   ref   pathIndexList);

                      int   indexListLength = pathIndexList.Count;
                      string [] np = pathValue.TrimStart( new   char [] {   '/'   }).Split( new   char [] {   '/'   });
                      for   ( int   i = 0; i < np.Length && indexListLength >= 1 + i; i++)
                    {
                        np[i] = np[i] +   "["   + pathIndexList[indexListLength - 1 - i].ToString() + "]" ;
                    }

                      //node.Attributes["w:xpath"].Value = pathValue;
                    node.Attributes[ "w:xpath" ].Value =   "/"   +   string .Join( "/" , np);
                }
            }
            groupNode.InnerXml = groupDoc.InnerXml;

        }
          protected   void   CheckNodeIndex( XmlNode   checkNode,   ref   List < int > indexList)
        {
              int   index = 0;
              if   (checkNode.ParentNode !=   null )
            {
                  foreach   ( XmlNode   node   in   checkNode.ParentNode.ChildNodes)
                {
                      if   (node.Name.Equals(checkNode.Name) && node != checkNode)
                    {
                        index++;
                    }
                      else   if   (node == checkNode)
                    {
                        index++;
                          break ;
                    }
                }
                indexList.Add(index);

                CheckNodeIndex(checkNode.ParentNode,   ref   indexList);
            }
        }
          private   XmlDocument   groupDoc =   new   XmlDocument ();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值