簡體   English   中英

如何使用Word Interop將新行添加到C#中的現有Word文檔表中?

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

所以,我有這個Word Document模板,里面有一個現有的表格。 我在查找有關如何在現有表上插入新行的引用時遇到一些困難。

我想知道的第一件事是,如何識別Word文檔模板中的表是否為現有表?

其次,如何用數據填充表格?

我嘗試將此鏈接作為參考https://msdn.microsoft.com/zh-cn/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++;

}

此代碼可以正常工作。 我現在唯一的問題是識別現有表。

這個答案已經很晚了,但是如果您沒有弄清楚的話:

您可以在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