如何以编程方式在Word文档中生成多个表格
How to generate multiple tables in Word Document programmatically
我正在尝试创建一个 MS Word 文档,其中包含多个位于彼此下方的表格。
以下代码导致错误消息 "Requested Member of the Collection Does Not Exist"。我知道我要在之前的表格中插入新表格,我只是不知道如何在下面创建新表格。
object myMissingValue = System.Reflection.Missing.Value;
Word._Application myApp = new Word.Application();
Word._Document myDocument = WordApplication.Documents.Add(ref myMissingValue, ref myMissingValue, ref myMissingValue, ref myMissingValue);
Word.Range myRange = myDocument.Range(ref myMissingValue, ref myMissingValue);
for (int i = 0; i < 5; i++)
{
myDocument.Tables.Add(myRange, 2, 2, ref myMissingValue, ref myMissingValue);
Word.Table myTable = WordDocument.Tables[i];
myTable.Range.Borders.Enable = 1;
myTable.Rows[1].Cells[1].Range.Text = "Table number " + Convert.ToString(i);
}
我想出了答案。我将Range设置为每次循环结束时文档内容的最后一个索引-1。
myRange = myDocument.Range(myDocument.Content.End - 1, ref myMissingValue);
我正在尝试创建一个 MS Word 文档,其中包含多个位于彼此下方的表格。
以下代码导致错误消息 "Requested Member of the Collection Does Not Exist"。我知道我要在之前的表格中插入新表格,我只是不知道如何在下面创建新表格。
object myMissingValue = System.Reflection.Missing.Value;
Word._Application myApp = new Word.Application();
Word._Document myDocument = WordApplication.Documents.Add(ref myMissingValue, ref myMissingValue, ref myMissingValue, ref myMissingValue);
Word.Range myRange = myDocument.Range(ref myMissingValue, ref myMissingValue);
for (int i = 0; i < 5; i++)
{
myDocument.Tables.Add(myRange, 2, 2, ref myMissingValue, ref myMissingValue);
Word.Table myTable = WordDocument.Tables[i];
myTable.Range.Borders.Enable = 1;
myTable.Rows[1].Cells[1].Range.Text = "Table number " + Convert.ToString(i);
}
我想出了答案。我将Range设置为每次循环结束时文档内容的最后一个索引-1。
myRange = myDocument.Range(myDocument.Content.End - 1, ref myMissingValue);