c# - 如何使用 Word Interop 在 C# 中向现有 Word 文档表添加新行?

标签 c# winforms ms-word office-interop

所以,我有这个 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++;

}

这段代码工作正常。我现在唯一的问题是识别现有的表。

最佳答案

这个答案太晚了,但以防万一您从未弄清楚:

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

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

关于c# - 如何使用 Word Interop 在 C# 中向现有 Word 文档表添加新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30881394/

相关文章:

c# - VB 函数 IsObject 的 C# 等效项是什么?

c# - User.Identity.Name 大小写问题

c# - 从字节数组创建位图

.net - 将光标定位在 Word 文档的开头/结尾

java - 将自定义形状添加到 JTextpane 并保存到新的 Word 文档

c# - 无法从 C# 代码访问 XAML 元素

c# - 具有 lambda 表达式的事件

c# - 使用 this.validateChildren() 时如何针对所有无效表单控件设置 errorProvider?

wpf - 在我的WPF应用程序中托管Windows Shell Explorer

vba - 如何向合并的Word表格添加行?