如何用文档

时间:2016-07-06 06:38:34

标签: c# ms-word mergefield

我有两个' DEMO'字

我希望用mergefield替换它

但只有一个' DEMO'使用我的代码改变了......

如何用字段替换文本?

感谢

        Application app = new Application();
        Document word = new Document();

        word = app.Documents.Add(ref path, ref missing, ref missing, ref missing);

        object objType = WdFieldType.wdFieldMergeField;

        object hashVal = null;
        Hashtable hash = new Hashtable();

        hash.Add("DEMO", "mergefield11111");


        foreach (object s in hash.Keys)
        {

            Range rng = app.ActiveDocument.Content;
            Find findObject = app.Selection.Find;

            object ff = s;
            hashVal = hash[s];       

            findObject.Text = ff.ToString();
            findObject.ClearFormatting();
            if (rng.Find.Execute(ref ff,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, WdReplace.wdReplaceOne, ref missing, ref missing,
            ref missing, ref missing))
            {
                Field field = app.Selection.Fields.Add(app.Selection.Range, ref objType, ref hashVal, ref missing);
            }
        }
        app.Documents.Open("test1.docx");

2 个答案:

答案 0 :(得分:0)

您只进行了一次Find操作。而是尝试while (rng.Find.Execute(...)) { ... }

答案 1 :(得分:0)

您可以使用Open XML SDK 2.5。您可以将Office文件作为Big XML文件读取,然后您可以更改所需内容。

  1. 您必须将Word文件读为MemoryStream
  2.  public byte[] DocumentGenerator(String templatePath)
        {
            byte[] buffer;
            using (MemoryStream stream = new MemoryStream())
            {
                buffer = System.IO.File.ReadAllBytes(templatePath);
                stream.Write(buffer, 0, buffer.Length);
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
                {
                   //Get list bookmarks
                    var listBookMarks = wordDocument.MainDocumentPart.Document.Descendants<BookmarkStart>().ToList();
                    //Get list Merge Fields
                    var listMergeFields = wordDocument.MainDocumentPart.Document.Descendants<FieldCode>().ToList();
                    //Do some code
                    wordDocument.Close();
                }
                buffer = stream.ToArray();
            }
    
            return buffer;
        }
    
    1. 然后,您可以更改文本,添加段落,添加表格或其他。您可以使用Office文件执行所有操作。 (Word,Excel ......) 这是我的例子。我尝试在我的书签字段中添加项目符号列表:
    2.             if (bookmark != null)
              {
                  var parent = bookmark.Parent;   // bookmark's parent element
                  var childEllement = parent.Elements<Run>().Last();
                  var lastChild = childEllement.LastChild;
                  childEllement.RemoveChild(lastChild);
      
      
                  foreach (var itemChild in groupList)
                  {
      
                      Paragraph paragraph1 = new Paragraph();
                      ParagraphProperties paragraphProperties = new ParagraphProperties();
                      ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
                      Tabs tabs = new Tabs();
                      TabStop tabStop1 = new TabStop() { Val = TabStopValues.Left, Position = 284 };
      
                      tabs.Append(tabStop1);
                      SpacingBetweenLines spacingBetweenLines1 = new SpacingBetweenLines() { After = "120", Line = "360", LineRule = LineSpacingRuleValues.Auto };
                      Indentation indentation1 = new Indentation() { Left = "0", FirstLine = "0" };
                      Justification justification = new Justification() { Val = JustificationValues.Both };
      
                      ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
      
                      paragraphProperties.Append(paragraphStyleId1);
                      paragraphProperties.Append(tabs);
                      paragraphProperties.Append(spacingBetweenLines1);
                      paragraphProperties.Append(indentation1);
                      paragraphProperties.Append(justification);
                      paragraphProperties.Append(paragraphMarkRunProperties1);
                      Run run1 = new Run();
                      RunProperties runProperties1 = new RunProperties();
      
                      Bold bold2 = new Bold();
                      FontSizeComplexScript fontSizeComplexScript2 = new FontSizeComplexScript() { Val = "24" };
      
                      runProperties1.Append(bold2);
                      runProperties1.Append(fontSizeComplexScript2);
                      Text text1 = new Text();
                      text1.Text = "- " + itemChild + ";";
                      run1.Append(runProperties1);
                      run1.Append(text1);
                      paragraph1.Append(paragraphProperties);
                      paragraph1.Append(run1);
                      parent.InsertAfterSelf(paragraph1);
                  }
              }
      
      1. 您可以使用Open XML SDK 2.5 Productivity Tool 阅读任何文件。此程序将帮助您了解文件结构。 祝你好运!