通过代码将Word 2007 template (dotx)文档转换Word 2007 (docx)文档(续)

在转换中间,需要把template中的Mail Merge Field去掉。Mail Merge Field的字符格式是:'MERGEFIELD  MyFieldName  \\* MERGEFORMAT',而对应的XML Node为:

   1: <w:fldSimple w:instr="MERGEFIELD FIELD_SYSTEM_DATE \m \* MERGEFORMAT">
   2:     <w:r>
   3:         <w:rPr>
   4:             <w:noProof /> 
   5:         </w:rPr>
   6:         <w:t>«FIELD_SYSTEM_DATE»</w:t> 
   7:     </w:r>
   8: </w:fldSimple>

我们要想办法把这个Node去掉,并且用

   1: <w:r>
   2:   <w:t>System Date</w:t> 
   3: </w:r>

来代替。

因为在之前的文章,我们可以知道dotx中的document.xml已经得到并且处理为一个XmlDocument Object了。我们可以通过这个XmlDocument来处理相关的节点。

当然是先设置一个XmlNamespaceManager:

   1: const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
   2:  
   3: //  Manage namespaces to perform Xml XPath queries.
   4: NameTable nt = new NameTable();
   5: XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
   6: nsManager.AddNamespace("w", wordmlNamespace);

然后,将之前的XmlDocument Object处理一下:

   1: // parse the document.xml
   2: XmlDocument xdoc = new XmlDocument(nt);
   3: xdoc.Load(documentPart.GetStream());

接着就该把Mail Merge Field分离了:

   1: int iTotalFields = 0;
   2:  
   3: XmlNodeList nodeList = xdoc.SelectNodes("//w:fldSimple", nsManager);
   4: foreach (XmlNode node in nodeList)
   5: {
   6:     // Create text node
   7:     XmlNode newNode = xdoc.CreateNode(XmlNodeType.Element, "w", "r", nsManager.LookupNamespace("w"));
   8:     XmlNode newChildNode = xdoc.CreateNode(XmlNodeType.Element, "w", "t", nsManager.LookupNamespace("w"));
   9:  
  10:     String fieldText = node.Attributes[0].Value;
  11:  
  12:     // only getting the mailmerge fields
  13:     if (fieldText.StartsWith(" MERGEFIELD"))
  14:     {
  15:         // The text comes in the format of 'MERGEFIELD  MyFieldName  \\* MERGEFORMAT'
  16:         // This has to be edited to get only the fieldname "myfieldname"
  17:         Int32 endMerge = fieldText.IndexOf("\\");
  18:         Int32 fieldNameLength = fieldText.Length - endMerge;
  19:         String fieldName = fieldText.Substring(11, endMerge - 11);
  20:  
  21:         // Gives the fieldnames as the user had entered in .dot file
  22:         fieldName = fieldName.Trim();
  23:  
  24:         // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
  25:         switch (fieldName)
  26:         {
  27:             case "FIELD_SYSTEM_DATE":
  28:                 newChildNode.InnerText = DateTime.Now.ToString("dd/MM/yyyy");
  29:                 break;
  30:         }
  31:     }
  32:     newNode.AppendChild(newChildNode);
  33:  
  34:     node.ParentNode.ReplaceChild(newNode, node);
  35:  
  36:     iTotalFields++;
  37: }
这样就处理好了有Mail merge field的Word template文档了。
posted @ 2008-06-28 00:03 David Views(...) Comments(...) Edit 收藏
Freelance Jobs