a lot of missingObj to avoid mistakes
Target.Net 4.0 or higher supports named and optional arguments with COM calls, so you don't need to include all ref missingObj . See MSDN Article: Named and Optional Arguments - This feature greatly facilitates calling COM interfaces, such as the Microsoft Office Automation API.
What do I need to change so that I can search using the DataTable instead of the string variable strToFindObj ?
You will need to go through the DataTables Row and Cell, replacing the DataTable cells in the Word Document, for example:
foreach(var dr in dt.Rows) { foreach (var cell in dr.ItemArray) { string strToFind = cell.ToString(); string replaceStr = "replace old value"; ReplaceTextInWord(@"C:\Temp\template.docx", strToFind, replaceStr); } }
If you use DataTable too much and want a list (like a dictionary) even easier:
var listOfTextToReplace = new Dictionary<string,string>(); listOfTextToReplace.Add("%%mark%%","text to replace"); foreach(var item in listOfTextToReplace ) { string strToFind = item.Key; string replaceStr = item.Value; ReplaceTextInWord(@"C:\Temp\template.docx", strToFind, replaceStr); }
Here is the ReplaceTextInWord method:
using Word = Microsoft.Office.Interop.Word; Word._Application application; Word._Document document; Object missingObj = System.Reflection.Missing.Value; Object trueObj = true; Object falseObj = false; private void create_button1_Click(object sender, EventArgs e) { //ReplaceTextInWord("template.dot", "find me", "Found"); <-- Are you sure you want to replace in a Template? ReplaceTextInWord(@"C:\Temp\template.docx", "%%mark%%","text to replace"); //I think you want a .DOC or DOCX file } private void ReplaceTextInWord(string wordDocFilePath, string strToFind, string replaceStr) { application = new Word.Application(); try { //document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); document = application.Documents.Open(wordDocFilePath); //You need to open Word Documents, not add them, as per https://msdn.microsoft.com/en-us/library/tcyt0y1f.aspx } catch (Exception error) { document.Close(ref falseObj, ref missingObj, ref missingObj); application.Quit(ref missingObj, ref missingObj, ref missingObj); document = null; application = null; throw error; } for (int i = 1; i <= document.Sections.Count; i++) { Word.Range wordRange = document.Sections[i].Range; Word.Find findObject = wordRange.Find; findObject.ClearFormatting(); findObject.Text = strToFind; findObject.Replacement.ClearFormatting(); findObject.Replacement.Text = replaceStr; object replaceAll = Word.WdReplace.wdReplaceAll; findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing); } application.Visible = true; }
Ref MSDN: A Practical Guide. Search and replace text in documents .