Microsoft Word / Replacing text

I just got a project to create a webpage that when a user clicks on a button, the webpage will replace some pieces of text in a word document.  The word document has some pictures, but here is a snippet of the layout.  All items in brackets will need to be replaced with data from a dataset.  Is it possible to stream the document and just use the .net string replace function?  But would I lose the word documents formatting or style??  Or what is the best way??  Currently this is a word document and not a word template.


[Date]



[CUName]
[CUAddress]



Dear [AdresseeName]


Sincerely,      
 
Test                                    
LVL 1
macros14Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
GavinMannionConnect With a Mentor Commented:
You will need to use the Word API that comes with .Net

Here is a quick C# script on how to read the word document. You will then need to update as required and then save it again. Remember to reference the Word API in your references.

public System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject();
public bool ReadWordDocument(string filePath)
        {
            Microsoft.Office.Interop.Word.Application wap = new Microsoft.Office.Interop.Word.ApplicationClass();
            object missing = System.Reflection.Missing.Value;
            object fileName = System.Environment.CurrentDirectory + "\\" + filePath;
            object objFalse = false;
            object objTrue = true;
            try
            {
               
                Microsoft.Office.Interop.Word.Document wdoc = wap.Documents.Open(ref fileName, ref objFalse, ref objTrue,
                 ref objFalse, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref objTrue,
                ref missing, ref missing, ref missing, ref missing);

                wdoc.ActiveWindow.Selection.WholeStory();
                wdoc.ActiveWindow.Selection.Copy();

                Contents = data.GetData(System.Windows.Forms.DataFormats.Html).ToString();
                Contents = Contents.Replace("Â", "").Replace("…", "...");
                wap.Application.Quit(ref missing, ref missing, ref missing);
                return true;
            }
            catch (Exception exc)
            {
                wap.Application.Quit(ref missing, ref missing, ref missing);
                return false;
            }
        }
0
All Courses

From novice to tech pro — start learning today.