您如何使用 Microsoft Office Word Interop 与复制+粘贴的 Table 进行交互?粘贴 table 不会添加到 document.Tables.count

How can you interact with a copied+pasted Table using Microsoft Office Word Interop? Pasted table doesn't add to document.Tables.count

我正在使用以下代码复制和粘贴 table:

Word.Table tableTemplate = document.Tables[tableNumber];
tableTemplate.Select();
word.Selection.Copy();    //word is my Word.Application
word.Selection.MoveDown(Word.WdUnits.wdLine, 2);
word.Selection.PasteAndFormat(Word.WdRecoveryType.wdTableOriginalFormatting);
table = document.Tables[tableNumber + 1];

不幸的是,粘贴 table 时 document.Tables.Count 变量没有递增,最后一行抛出索引越界错误。我确定这是我遗漏的一些小东西。

如果有类似问题的人正在寻找解决方案,我在 table 下方放置了一个书签,将选择光标移动到那里,然后选择书签前的范围并粘贴。

Word.Bookmark bkmrk = document.Bookmarks["MyBkmrk"];
Word.Range rng = document.Range(bkmrk.Range.Start - 1, bkmrk.Range.Start - 1);
rng.Select();
word.Selection.Paste();

这似乎比尝试使用 MoveDown 更有效。我什至尝试在选择中使用 MoveDown,方法是使用范围内的段落数来确定多远,但这完全行不通。

编辑:

所以,我真正的问题是我需要复制一个 table 并循环粘贴其中的一些,然后编辑 table 的内容。我将 运行 保存到 table 粘贴到自身中,并且通常被搞砸了。对于任何需要做类似事情的人,这里有一些帮助:

Word.Table table = document.Tables[tableNumber];
table.Select();
wordApplication.Selection.Copy();
for(int i = 0; i < tablesINeed; i++)
{
    Word.Range rng = document.Range(document.Tables[tableNumber + i].Range.End + 1, document.Tables[tableNumber + i].Range.End + 1);
    rng.Select();
    wordApplication.Selection.Paste();
    // Modify table accordingly
}

看似简单,实则历经千辛万苦。希望它能对某人有所帮助。

我有一个基于 cboler 的答案。如果 table 后面已经有东西要复制,我会遇到问题。

private static List<Table> CloneTables(Application Application, Document doc, int tableNumber, int tablesINeed)
    {
        List<Table> sameTables = new List<Table>();
        Table lastTable = doc.Tables[tableNumber];
        sameTables.Add(lastTable);

        lastTable.Select();
        Application.Selection.Copy();
        for (int i = 0; i < tablesINeed; i++)
        {
            lastTable.Range.Next().InsertParagraphAfter();
            Range rng = doc.Range(doc.Tables[tableNumber + i].Range.End + 1, doc.Tables[tableNumber + i].Range.End + 1);
            rng.Select();
            Application.Selection.Paste();
            lastTable = doc.Tables[tableNumber + i + 1];
            sameTables.Add(lastTable);
        }

        return sameTables;
    }