Tables 集合是 Microsoft.Office.Interop.Word.Document、Microsoft.Office.Tools.Word.Document、Selection 和 Range 类的成员,这意味着您可以在其中任何上下文中创建一个表。 可以使用 Tables 集合的 Add 方法在指定的范围添加表。
向文档中添加简单的表
Word.Range tableLocation = this.Application.ActiveDocument.Range(0, 0);
this.Application.ActiveDocument.Tables.Add( tableLocation, 3, 4); //三行四列
通过项编号引用表
Word.Table newTable = this.Application.ActiveDocument.Tables[1];
每个 Table 对象还有一个 Range 属性,通过该属性可以设置格式设置特性。
this.Application.ActiveDocument.Tables[1].Range.Font.Size = 8;
this.Application.ActiveDocument.Tables[1].set_Style("Table Grid 8");
用文档属性填充 Word 表
1 将范围设置为文档开头。
object start = 0, end = 0;
Word.Document document = this.Application.ActiveDocument;
Word.Range rng = document.Range(ref start, ref end);
2 插入表的标题并包括段落标记。
rng.InsertBefore("Document Statistics");
rng.Font.Name = "Verdana";
rng.Font.Size = 16;
rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
rng.SetRange(rng.End, rng.End);
3 将表添加到文档中的该范围内。
rng.Tables.Add(document.Paragraphs[2].Range, 3, 2, ref missing, ref missing);
4 设置表格式并应用样式。
Word.Table tbl = document.Tables[1];
tbl.Range.Font.Size = 12;
tbl.Columns.DistributeWidth();
object styleName = "Table Professional";
tbl.set_Style(ref styleName);
5 将文档属性插入到单元格中。
tbl.Cell(1, 1).Range.Text = "Document Property";
tbl.Cell(1, 2).Range.Text = "Value";
tbl.Cell(2, 1).Range.Text = "Subject";t
bl.Cell(2, 2).Range.Text = ((Office.DocumentProperties)(document.BuiltInDocumentProperties)) [Word.WdBuiltInProperty.wdPropertySubject].Value.ToString();t
bl.Cell(3, 1).Range.Text = "Author";
tbl.Cell(3, 2).Range.Text = ((Office.DocumentProperties)(document.BuiltInDocumentProperties)) [Word.WdBuiltInProperty.wdPropertyAuthor].Value.ToString();
向 Word 表添加行和列
在 Microsoft Office Word 表中,单元格被组织为行和列。 可以使用 Rows 对象的 Add 方法向表中添加行;使用 Columns 对象的 Add 方法添加列。
向表中添加行
this.Application.ActiveDocument.Tables[1].Rows.Add( this.Application.ActiveDocument.Tables[1].Rows[1]);
向表中添加列
使用 Add 方法,然后再使用 DistributeWidth 方法使所有的列具有相同的宽度。
this.Application.ActiveDocument.Tables[1].Columns.Add( this.Application.ActiveDocument.Tables[1].Columns[1]);
this.Application.ActiveDocument.Tables[1].Columns.DistributeWidth();
向 Word 表中的单元格添加文本和格式设置
Word.Cell cell = this.Application.ActiveDocument.Tables[1].Cell(1, 1);
cell.Range.Text = "Name";
cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;