简体   繁体   English

遍历Microsoft Word文档以查找和替换表

[英]Iterate through a Microsoft Word document to find and replace tables

I have some VBA code that iterates through a document to remove tables from a document. 我有一些VBA代码,可以遍历文档以从文档中删除表。 The following code works fine in VBA: 以下代码在VBA中可以正常运行:

Set wrdDoc = ThisDocument
With wrdDoc
    For Each tbl In wrdDoc.Tables
        tbl.Select
        Selection.Delete
    Next tbl
End With

Unfortunately, I cannot easily translate this code to C#, presumably because there is a newer Range.Find method. 不幸的是,我无法轻松地将此代码转换为C#,大概是因为有一个更新的Range.Find方法。 Here are three things I tried, each failing. 这是我尝试过的三件事,每件事都失败了。

First attempt (re-write of the VBA code): 首次尝试(重写VBA代码):

foreach (var item in doc.Tables)
{
  item.Delete; //NOPE! No "Delete" function.
}

I tried this: 我尝试了这个:

doc = app.Documents.Open(sourceFolderAndFile); //sourceFolderAndFile opens a standard word document.
var rng = doc.Tables;
foreach(var item in rng)
{
  item.Delete; //NOPE! No "Delete" function.
}

I also tried this: 我也试过这个:

doc = app.Documents.Open(sourceFolderAndFile); //sourceFolderAndFile opens a standard word document.
var rng = doc.Tables;
Range.Find.Execute(... //NOPE! No Range.Find available for the table collection.
...

Could someone please help me understand how I can use C# and Word Interop (Word 2013 and 2016) to iterate through a document, find a table, and then perform a function, like selecting it, deleting it, or replacing it? 有人可以帮助我了解如何使用C#和Word Interop(Word 2013和2016)遍历文档,查找表并执行功能,例如选择,删除或替换它吗?

Thanks! 谢谢!

It took me some time to figure this answer out. 我花了一些时间弄清楚这个答案。 With all the code samples online, I missed the need to create an app. 有了所有在线代码示例,我错过了创建应用程序的需要。 For posterity, here is how I resolved the problem. 为了后代,这是我解决问题的方式。

  1. Make sure you have a Using statement, like this: 确保您有一个Using语句,如下所示:

    using MsWord = Microsoft.Office.Interop.Word; 使用MsWord = Microsoft.Office.Interop.Word;

  2. Open the document and then work with the new msWord reference, the range, and the table. 打开文档,然后使用新的msWord参考,范围和表格。 I provide a basic example below: 我在下面提供一个基本示例:

      //open the document. doc = app.Documents.Open(sourceFolderAndFile, ReadOnly: true, ConfirmConversions: false); //iterate through the tables and delete them. foreach (MsWord.Table table in doc.Tables) { //select the area where the table is located and delete it. MsWord.Range rng = table.Range; rng.SetRange(table.Range.End, table.Range.End); table.Delete(); } //don't forget doc.close and app.quit to clean up memory. 

You can use the Range (rng) to replace the table with other items, like text, images, etc. 您可以使用范围(rng)将表格替换为其他项,例如文本,图像等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM