Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Intro

Excerpt

Demonstrates how to use regular expressions with WordWriter to easily search and replace text.

This sample uses the WordApplication class to open an existing document on the server and perform search and replace actions on it. First, view the stored document to determine which patterns to search for (search terms that work well are WordWriter, and template). Remember that Regular Expressions are case sensitive. So, to search for "WordWriter" "Wordwriter", use this pattern: Word[Ww]riter.

Code

Code Block
private string recipName = "Bradley Smith"; private  string recipStreetAddrSearchPattern = "123 College Street[Ww]ord[Ww]riter";
private string recipCity = "Boston"; private   string recipStatereplaceWith = "MASoftArtisans";
private string recipZip = "02201-1020"; private   string authNamedocPath = "John Doyle@"..\..\WordTemplateFiles\SearchReplace.doc";
private
string authTitle = "Mr."; private string fontName = "Arial";
private double fontSize = 10;

 /// <summary>
        /// <summary>
Searches a document for a Regular Expression search term
        /// Buildand thereplaces report with WordTemplate.  Then pass it to WordApplication for formatting.
all instances of that term with a new string.
        /// The revised document is then saved.
        /// </summary>
        public void GenerateDocumentSearchDocument()
        {
 // Form the required WordWriter name array.  The elements    /// inOpen thisthe arraydocument correspondyou wish to thesearch
names
of the  // merge fields in the template, and each element's WordApplication array wordApp = // index should correspond to an element in the value array

 string[] arrNames = {"RecipientName", "RecipientStreetAddr", "RecipientCity", 
 "RecipientState", "RecipientZip", "AuthorName", "AuthorTitle"};

 // The value array.  The value of the elements in this array 
 // contain info supplied in the web form. These values 
 // represent the data that will be dynamically populated 
 // in the template file.

 object[] arrValues = {recipName, recipStreetAddr, recipCity, 
  recipState, recipZip, authName, authTitle};


 // Create the WordTemplate object 
 SoftArtisans.OfficeWriter.WordWriter.WordTemplate wt = new SoftArtisans.OfficeWriter.WordWriter.WordTemplate();

 // Open the template document 
 string templatePath = @"..\..\Templates\FormLetterFormattingTemplate.doc";
 wt.Open(templatePath);

 // Set the datasource with the name and value arrays defined above 
 wt.SetDataSource(arrValues, arrNames);

 // Process the template 
 wt.Process();

 // Create the WordApplication object 
 WordApplication wwapp = new WordApplication();

 // Open the processed WordTemplate document for formatting 
 Document doc = wwapp.Open(wt);

 // Format the document with the selected font and font size 
 FormatCharacterRuns(doc);

 // Save the document by streaming it 
  // to the client's browser 
  
 wwapp.Save(doc, @"..\..\Output\FormLetterFormatted_out.doc");
}

// Formats all CharacterRuns in the specified Element with the specified font name and size 
private void FormatCharacterRuns(Element e)
{
 // If this element is a CharacterRun, format it 
 if (e.ElementType == Element.Type.CharacterRun)
 {
 CharacterRun run = (CharacterRun) e;
 run.Font.FontName = this.fontName;
 run.Font.FontSize = this.fontSize;
 }

 // For each child of this element 
 foreach(Element child in e.Children)
 {
 // Call FormatCharacterRuns 
 FormatCharacterRuns(child);
 }
}


new WordApplication();
            Document doc = wordApp.Open(docPath);

            // Execute the replacement by specifying the search term
            // as a Regular Expression string, and the replacement string.
            // SearchAndReplace will return the number of replacements made.

            int numReplacements = doc.SearchAndReplace(SearchPattern, replaceWith);

            // If no occurrences of the search pattern were found in the doc, display
            // a message and return.

            if(numReplacements == 0)
            {
                Console.WriteLine("Note: No occurrences of \"{0}\" were found in the document. " +
                                "Please try another search pattern.", SearchPattern);
                return;
            }

            // Prepend a message to the beginning of the document noting
            // how many replacements were made.
            string text =
                String.Format("Replaced {0} instances of \"{1}\" with \"{2}\"",
                    numReplacements, SearchPattern, replaceWith);

            // Create a new paragraph and insert the note
            Paragraph pg = doc.InsertParagraphBefore(null);
            pg.InsertTextAfter(text, false);

            // Save the edited document
            wordApp.Save(doc, @"..\..\WordOutputFiles\Replaced_out.doc");
        }
    }



Downloads

Initial Document: SearchReplace.doc

...