繁体   English   中英

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

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

我有一些VBA代码,可以遍历文档以从文档中删除表。 以下代码在VBA中可以正常运行:

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

不幸的是,我无法轻松地将此代码转换为C#,大概是因为有一个更新的Range.Find方法。 这是我尝试过的三件事,每件事都失败了。

首次尝试(重写VBA代码):

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

我尝试了这个:

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

我也试过这个:

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.
...

有人可以帮助我了解如何使用C#和Word Interop(Word 2013和2016)遍历文档,查找表并执行功能,例如选择,删除或替换它吗?

谢谢!

我花了一些时间弄清楚这个答案。 有了所有在线代码示例,我错过了创建应用程序的需要。 为了后代,这是我解决问题的方式。

  1. 确保您有一个Using语句,如下所示:

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

  2. 打开文档,然后使用新的msWord参考,范围和表格。 我在下面提供一个基本示例:

      //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. 

您可以使用范围(rng)将表格替换为其他项,例如文本,图像等。

暂无
暂无

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

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