循环在word文档中添加表格

Adding tables in word document in loop

我想以编程方式在 word 文档中添加多个 table。我尝试了以下代码以添加 table (在下面的示例代码中我没有使用循环)

        Microsoft.Office.Interop.Word.Table imageTable1 = wordDoc.Tables.Add(initialRange, 1, 2, ref oMissing, ref oMissing);
        imageTable1.Rows.SetHeight(40, WdRowHeightRule.wdRowHeightExactly);
        imageTable1.AllowAutoFit = true;

        var text = "ABC";

        // Add feature name in bold in table
        if (!string.IsNullOrEmpty(text))
        {
            Cell cell1 = imageTable1.Cell(1, 1);
            cell1.Range.Bold = 1;
            cell1.Range.Underline = WdUnderline.wdUnderlineSingle;
            cell1.Range.Font.Size = 18;
            cell1.Range.Font.AllCaps = 1;
            cell1.Range.Font.Name = "Times New Roman";
            cell1.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            cell1.Range.Text = "ABC";
        }
        initialRange.Collapse(WdCollapseDirection.wdCollapseEnd);
        initialRange.InsertParagraphAfter();
        initialRange.Collapse(WdCollapseDirection.wdCollapseEnd);


        Microsoft.Office.Interop.Word.Table imageTable2 = wordDoc.Tables.Add(initialRange, 1, 2, ref oMissing, ref oMissing);
        imageTable2.Rows.SetHeight(40, WdRowHeightRule.wdRowHeightExactly);
        imageTable2.AllowAutoFit = true;

        text = "DEF"
        // Add feature name in bold in table
        if (!string.IsNullOrEmpty(text))
        {
            Cell cell1 = imageTable2.Cell(1, 1);
            //cell1.Range.InsertAfter(feature.Name + Environment.NewLine);
            cell1.Range.Bold = 1;
            cell1.Range.Underline = WdUnderline.wdUnderlineSingle;
            cell1.Range.Font.Size = 18;
            cell1.Range.Font.AllCaps = 1;
            cell1.Range.Font.Name = "Times New Roman";
            cell1.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            cell1.Range.Text = "DEF";
        }

在上面的代码中,initialRange 变量是我文档中的选择范围。使用上面的代码,我得到重叠的 tables 并且在打开文档时只有最后一个 table 是可见的。代码正确创建了所有 table,但所有 table 都放置在同一位置,因此最后创建的 table 仅可见。我无法弄清楚上面的代码需要进行哪些更改才能一个接一个地显示 table。

此外,我想在 table 之间添加一些文本行。如何插入文本,以便在我的文档中有 table 后跟相关文本。

谢谢

问题不在于 table 重叠。问题中的代码发生了什么是后续 table 被插入到前一个 table 中的单元格中。原因是因为 initialRange 不包含在范围内添加的整个 table - initialRange 在 table.

的第一个单元格中

诀窍是将 Range 对象放在 table 的末尾,像这样:

initialRange = imageTable1.Range;
initialRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
initialRange.InsertParagraphAfter();
initialRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);