zymurgy

zymurgy

  • NA
  • 1
  • 0

Automating Word (retain original formatting)

Apr 29 2007 3:38 AM

Hello,

I have a word document where I have gone in and replaced specific areas with replaceable text. My ultimate intention is to place these replaceable texts throughout the document and insert data from a database directly into the text file.

But I digress, the problem I'm running into right now is that the VS.NET 2003 web application I'm writing opens the file and replaces the text just fine, except that it changes the entire document to Times New Roman 12 font. Unfortunately, it's not as easy as selecting the entire document afterwards and changing it back since different places require different fonts and sizes. Is there a way to just retain the original document's formatting?

Word.ApplicationClass oWordApp = new Word.ApplicationClass();

object oFileName = "c:\\prewrittendocument.doc";

object readOnly = false;

object isVisible = true;

object missing = System.Reflection.Missing.Value;

Word.Document oWordDoc = oWordApp.Documents.Open(ref oFileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

oWordDoc.Activate();

oWordDoc.Select();

object findText = "%1";

object replaceText = "hi";

oWordApp.Selection.ClearFormatting(); //yes, I know this is here

oWordApp.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceText, ref missing, ref missing, ref missing, ref missing, ref missing);


Without the ClearFormatting() line, the program gives a compilation error during runtime:

Compiler Error Message: CS0006: Metadata file 'c:\windows\microsoft.net\framework\v1.1.4322\temporary asp.net files\webapplication1\8dd84b00\b065eec7\assembly\dl2\917ea1fe\00d52f11_208fc501\interop.microsoft.office.core.dll' could not be found

Source Error:

[No relevant source lines]

With the ClearFormatting line, the program actually does what it is supposed to, except it clears all the formatting.

Thanks