简体   繁体   English

如何使用Word Interop将新行添加到C#中的现有Word文档表中?

[英]How to add new rows to an existing word document table in C# using Word Interop?

So, I have this Word Document template with an existing table in it. 所以,我有这个Word Document模板,里面有一个现有的表格。 I am having some difficulties in finding references on how to insert new rows on the existing table. 我在查找有关如何在现有表上插入新行的引用时遇到一些困难。

First thing I want to know is, how will I identify if the table inside my word document template is the existing table? 我想知道的第一件事是,如何识别Word文档模板中的表是否为现有表?

Secondly, how will I populate the table with data? 其次,如何用数据填充表格?

I tried this link as a reference https://msdn.microsoft.com/en-us/library/vstudio/w1702h4a.aspx but don't know how to embed it to my program. 我尝试将此链接作为参考https://msdn.microsoft.com/zh-cn/library/vstudio/w1702h4a.aspx,但不知道如何将其嵌入到我的程序中。

I also tried creating new table as an alternative solution with the following code: 我还尝试使用以下代码创建新表作为替代解决方案:

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++;

} }

This code works fine. 此代码可以正常工作。 My only problem now is to identify an existing table. 我现在唯一的问题是识别现有表。

This answer is way late, but in case you never figured it out: 这个答案已经很晚了,但是如果您没有弄清楚的话:

You can set the alt text for the table within Word (right click > Table Properties > Alt Text), then use that to single out the desired table. 您可以在Word中为表格设置替代文字(右键单击>表格属性>替代文字),然后使用它来选择所需的表格。

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

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

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