【问题标题】:How to add new rows to an existing word document table in C# using Word Interop?如何使用 Word Interop 在 C# 中向现有 Word 文档表中添加新行?
【发布时间】:2016-08-30 01:32:40
【问题描述】:

所以,我有这个 Word 文档模板,其中包含一个现有表格。我在查找有关如何在现有表上插入新行的参考时遇到了一些困难。

首先我想知道的是,如何识别我的word文档模板中的表格是否是现有表格?

其次,我将如何用数据填充表格?

我尝试将此链接作为参考https://msdn.microsoft.com/en-us/library/vstudio/w1702h4a.aspx,但不知道如何将其嵌入到我的程序中。

我还尝试使用以下代码创建新表作为替代解决方案:

object m = System.Reflection.Missing.Value;
object oldFileName = (object)"E:\\Fake Bill.docx";
object readOnly = (object)false;
Word.Application ac = null;
ac = new Word.Application();

// Now we open the document.
Word.Document doc = ac.Documents.Open(ref oldFileName, ref m, ref readOnly,
     ref m, ref m, ref m, ref m, ref m, ref m, ref m,
     ref m, ref m, ref m, ref m, ref m, ref m);

object start = 0;
object end = 0;
Word.Range myRange = doc.Range(ref start, ref end);
Word.Table myTable = doc.Tables.Add(myRange, 2, 3);
int rowCount = 2; 

List<string> collectionOfStrings = new List<string>();
collectionOfStrings.Add("hello");
collectionOfStrings.Add("hi");


//add a row for each item in a collection.
foreach( string s in collectionOfStrings)

{
    myTable.Rows.Add(ref m);

    // do somethign to the row here. add strings etc. 
    myTable.Rows[rowCount].Cells[1].Range.Text = "Content of column 1";

    myTable.Rows[rowCount].Cells[2].Range.Text = "Content of column 2";

    myTable.Rows[rowCount].Cells[3].Range.Text = "Content of column 3";

    //etc
    rowCount++;

}

此代码运行良好。我现在唯一的问题是识别现有表。

【问题讨论】:

  • 如果表格已经存在于文档中,它应该可以使用 doc.Tables[] 访问。不是这样吗?
  • 你好@GER。我尝试使用 doc.Tables[] 但我总是得到一个错误:Object not set to an instance of an object.

标签: c# winforms ms-word office-interop


【解决方案1】:

这个答案来得太晚了,但万一你还没弄明白:

您可以在 Word 中为表格设置替代文本(右键单击 > 表格属性 > 替代文本),然后使用它来挑选所需的表格。

    foreach (Table table in myDocument.Tables)
    {
        if (table.Title == "table_alt_text")
        {
            // However you want to manipulate your table
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2013-07-04
    相关资源
    最近更新 更多