在循环中添加word文档中的表

问题描述 投票:0回答:1

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

        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变量是我的文档中的Selection范围。使用上面的代码,我得到重叠的表,只有在打开文档时才能看到最后一个表。代码正确创建所有表,但所有表都放在同一位置,因此最后创建的表只能看到。我无法弄清楚上面代码中需要进行哪些更改才能一个接一个地显示表格。

另外,我想在表之间添加一些文本行。我如何插入文本,以便在我的文档中我有表格及其相关文本。

谢谢

c# ms-word office-interop
1个回答
0
投票

问题不在于表格是重叠的。问题中的代码发生的是后续表被插入到上一个表中的单元格中。原因是因为initialRange不包含在Range中添加的整个表 - initialRange位于表的第一个单元格中。

诀窍是将Range对象放在表的末尾,如下所示:

initialRange = imageTable1.Range;
initialRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
initialRange.InsertParagraphAfter();
initialRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
© www.soinside.com 2019 - 2024. All rights reserved.