c# - 如何在Word文档中插入表格代替文本标记?

标签 c# datatable com ms-word ms-office

我有日期表。需要插入它而不是模板文档中的某些字符集。

我可以用这种方式替换文本到文本(很多 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 中的东西,什么是文档的一些片段,包括表格、格式等。

最佳答案

lots of missingObj to avoid the bugs

目标 .Net 4.0 或更高版本支持 COM 调用的命名参数和可选参数,因此您不需要包含所有 ref missingObj。请参阅这篇 MSDN 文章:Named and Optional Arguments - 此功能极大地促进了对 COM 接口(interface)(例如 Microsoft Office Automation API)的调用。


What do I have to change so I can search using a DataTable instead of string variable strToFindObj?

您必须遍历 DataTables 行和单元格以替换 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:How to: Programmatically Search for and Replace Text in Documents

关于c# - 如何在Word文档中插入表格代替文本标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31421684/

相关文章:

c# - 如何定义具有预定义容量的列表数组?

c# - 如何在 WIQL TFS 中知道 ID 是否有父 ID?

c# - 你如何在 wpf 中创建数据表?

python - 使用 win32COM 时创建新的 Python 对象

c# - ASP.Net - RadWindow 的最大化和关闭图标对齐问题

c# - 如何允许在 DataGridView 上插入?

c# - 替换 DataColumn 中的值

angular - 无法绑定(bind)到 'dataSource',因为它不是 'table' 的已知属性

c# - .NET 0x80040154 (REGDB_E_CLASSNOTREG) : Retrieving the COM class factory for component with CLSID {XXXX}

c++ - 将一个dll文件导入另一个IDL文件