如何将表格插入Word文档中替换文本标记?

7

我有一个 DateTable。需要将其插入到模板文档中的某些字符集合中。

我可以通过文本替换的方式来实现(使用大量的missingObj来避免错误):

    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) {
            application = new Word.Application();
            Object templatePathObj;
            templatePathObj = "template.dot";  

            try {
                document = application.Documents.Add(ref  templatePathObj, 
                    ref missingObj, ref missingObj, ref missingObj);
            }
            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;
            }

            object strToFindObj = "%%mark%%";
            object replaceStrObj = "text to replace";
            Word.Range wordRange;
            object replaceTypeObj;
            replaceTypeObj = Word.WdReplace.wdReplaceAll;
            for (int i = 1; i <= document.Sections.Count; i++) {
                wordRange = document.Sections[i].Range;
                Word.Find wordFindObj = wordRange.Find;
                object[] wordFindParameters = new object[15] { strToFindObj, missingObj, 
                    missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, 
                    missingObj, replaceStrObj, replaceTypeObj, missingObj, missingObj, 
                    missingObj, missingObj };
                wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, 
                    null, wordFindObj, wordFindParameters);
        }
        application.Visible = true;
    }

我需要改变什么,使得这段代码可以使用DataTable而不是strToFindObj?

在这个例子中,我替换了Range中的内容,这些内容是文档的一部分,包括表格、格式等。

1个回答

5

为避免错误,需要使用许多缺失对象

.Net 4.0或以上版本支持使用命名参数和可选参数进行COM调用,因此您无需包含所有ref missingObj。请参阅此MSDN文章:命名和可选参数 - 此功能极大地简化了对COM接口(如Microsoft Office Automation API)的调用。


我需要更改什么才能使用DataTable进行搜索,而不是使用字符串变量strToFindObj

您需要遍历DataTable的行和单元格,并替换Word文档中的DataTable单元格,例如:

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);
  }
}

如果您觉得使用 DataTable 太困难,想要一个更简单的列表(类似于字典):
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);
}

这里是ReplaceTextInWord方法:

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;
}

参考MSDN:如何:以编程方式搜索并替换文档中的文本


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接