创建一个表

Aspose.Words 允许用户从头开始在文档中创建表格,并提供了几种不同的方法来执行此操作。本文详细介绍了如何使用每种方法将格式化表格添加到文档中,并在文章末尾对每种方法进行了比较。

默认表格样式

新创建的表被赋予与 Microsoft Word 中使用的默认值类似的默认值:

表属性 Aspose.Words 中的默认值
Border Style Single
Border Width 1/2 pt
Border Color Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

使用 DocumentBuilder 创建表

在 Aspose.Words 中,用户可以使用 DocumentBuilder 在文档中创建表格。创建表的基本算法如下:

1.用StartTable启动表 2. 使用 InsertCell 将单元格添加到表格中 – 这会自动开始一个新行 3. (可选)使用 CellFormat 属性指定单元格格式 4. 使用适当的 DocumentBuilder 方法(例如 WritelnInsertImage 等)插入单元格内容 5. 重复步骤 2-4,直至完成该行 6.调用EndRow结束当前行 7. (可选)使用 RowFormat 属性指定行格式 8. 重复步骤 2-7,直到表格完成 9.调用EndTable完成建表

创建表的过程可以清晰地看到下图:

creating-table-process

以下代码示例演示如何使用 DocumentBuilder 使用默认格式创建一个简单的表:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Start building the table.
builder.StartTable();
builder.InsertCell();
builder.Write("Row 1, Cell 1 Content.");
// Build the second cell.
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.EndRow();
// Build the first cell of the second row.
builder.InsertCell();
builder.Write("Row 2, Cell 1 Content");
// Build the second cell.
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content.");
builder.EndRow();
// Signal that we have finished building the table.
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.CreateSimpleTable.docx");

以下代码示例演示如何使用 DocumentBuilder 创建格式化表:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
builder.InsertCell();
// Table wide formatting must be applied after at least one row is present in the table.
table.LeftIndent = 20.0;
// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;
builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");
// We don't need to specify this cell's width because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// Reset height and define a different height rule for table body.
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();
builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.FormattedTable.docx");

以下代码示例演示如何使用 DocumentBuilder 插入嵌套表:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Cell cell = builder.InsertCell();
builder.Writeln("Outer Table Cell 1");
builder.InsertCell();
builder.Writeln("Outer Table Cell 2");
// This call is important to create a nested table within the first table.
// Without this call, the cells inserted below will be appended to the outer table.
builder.EndTable();
// Move to the first cell of the outer table.
builder.MoveTo(cell.FirstParagraph);
// Build the inner table.
builder.InsertCell();
builder.Writeln("Inner Table Cell 1");
builder.InsertCell();
builder.Writeln("Inner Table Cell 2");
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.NestedTable.docx");
view raw nested-table.cs hosted with ❤ by GitHub

通过 DOM (Document Object Model) 创建表

您可以通过在特定位置添加新的 Table 节点来将表格直接插入到 DOM 中。

请注意,表节点创建后,表本身将完全为空,即它还不包含行和单元格。要将行和单元格插入表中,请将适当的 RowCell 子节点添加到 DOM。

以下代码示例演示如何通过向文档树添加适当的子节点来从头开始构建新表:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
// We start by creating the table object. Note that we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
doc.FirstSection.Body.AppendChild(table);
// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid. In this case, a valid table should have at least one Row and one cell.
// Instead, we will handle creating the row and table ourselves.
// This would be the best way to do this if we were creating a table inside an algorithm.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));
row.AppendChild(cell);
// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));
// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableDirectly.docx");

从 HTML 创建表格

Aspose.Words 支持使用 InsertHtml 方法将内容从 HTML 源插入到文档中。输入可以是完整的 HTML 页面或只是部分片段。

使用InsertHtml方法,用户可以通过<table><tr><td>等表格标签将表格插入到文档中。

以下代码示例演示如何将表格从包含 HTML 标记的字符串插入到文档中:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Note that AutoFitSettings does not apply to tables inserted from HTML.
builder.InsertHtml("<table>" +
"<tr>" +
"<td>Row 1, Cell 1</td>" +
"<td>Row 1, Cell 2</td>" +
"</tr>" +
"<tr>" +
"<td>Row 2, Cell 2</td>" +
"<td>Row 2, Cell 2</td>" +
"</tr>" +
"</table>");
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableFromHtml.docx");

插入现有表的副本

很多时候,您需要根据文档中已有的表格创建表格。在保留所有格式的同时复制表的最简单方法是使用 Clone 方法克隆表节点。

可以使用相同的技术将现有行或单元格的副本添加到表中。

以下代码示例演示如何使用节点构造函数复制表:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
// Clone the table and insert it into the document after the original.
Table tableClone = (Table) table.Clone(true);
table.ParentNode.InsertAfter(tableClone, table);
// Insert an empty paragraph between the two tables,
// or else they will be combined into one upon saving this has to do with document validation.
table.ParentNode.InsertAfter(new Paragraph(doc), table);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneCompleteTable.docx");

以下代码示例演示如何克隆表的最后一行并将其附加到表中:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
Row clonedRow = (Row) table.LastRow.Clone(true);
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
foreach (Cell cell in clonedRow.Cells)
cell.RemoveAllChildren();
table.AppendChild(clonedRow);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneLastRow.docx");

如果您正在考虑在文档中创建随数据源中的每条记录动态增长的表,则不建议使用上述方法。相反,通过使用带有区域的 Mail merge 可以更轻松地实现所需的输出。您可以在 Mail Merge 与区域 部分了解有关此技术的更多信息。

比较创建表的方法

Aspose.Words 提供了多种在文档中创建新表格的方法。每种方法都有其自身的优点和缺点,因此选择使用哪种方法通常取决于具体情况。

让我们仔细看看这些创建表的方法并比较它们的优缺点:

方法 优点 缺点
通过DocumentBuilder 插入表格和其他文档内容的标准方法 有时很难使用同一个构建器实例同时创建多种表
通过DOM 更适合周围的代码,无需使用 DocumentBuilder 即可直接创建节点并将其插入到 DOM 中 该表被创建为"空":在执行大多数操作之前,必须调用 EnsureMinimum 创建任何丢失的子节点
来自 HTML 可以使用 <table><tr><td> 等标签从 HTML 源创建新表 并非所有可能的 Microsoft Word 表格格式都可以应用于 HTML
克隆现有表 您可以创建现有表格的副本,同时保留所有行和单元格格式 在表可供使用之前,必须删除适当的子节点