创建表

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

默认表样式

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

表属性 Aspose.Words中的默认值
Border Style Single
Border Width 1/2pt
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-C.git.
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Start building the table.
builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, Cell 1 Content.");
// Build the second cell.
builder->InsertCell();
builder->Write(u"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(u"Row 2, Cell 1 Content");
// Build the second cell.
builder->InsertCell();
builder->Write(u"Row 2, Cell 2 Content.");
builder->EndRow();
// Signal that we have finished building the table.
builder->EndTable();
doc->Save(ArtifactsDir + u"WorkingWithTables.CreateSimpleTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
// Table wide formatting must be applied after at least one row is present in the table.
table->set_LeftIndent(20.0);
// Set height and define the height rule for the header row.
builder->get_RowFormat()->set_Height(40.0);
builder->get_RowFormat()->set_HeightRule(HeightRule::AtLeast);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::FromArgb(198, 217, 241));
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_Font()->set_Size(16);
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Bold(true);
builder->get_CellFormat()->set_Width(100.0);
builder->Write(u"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(u"Header Row,\n Cell 2");
builder->InsertCell();
builder->get_CellFormat()->set_Width(200.0);
builder->Write(u"Header Row,\n Cell 3");
builder->EndRow();
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_White());
builder->get_CellFormat()->set_Width(100.0);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
// Reset height and define a different height rule for table body.
builder->get_RowFormat()->set_Height(30.0);
builder->get_RowFormat()->set_HeightRule(HeightRule::Auto);
builder->InsertCell();
// Reset font formatting.
builder->get_Font()->set_Size(12);
builder->get_Font()->set_Bold(false);
builder->Write(u"Row 1, Cell 1 Content");
builder->InsertCell();
builder->Write(u"Row 1, Cell 2 Content");
builder->InsertCell();
builder->get_CellFormat()->set_Width(200.0);
builder->Write(u"Row 1, Cell 3 Content");
builder->EndRow();
builder->InsertCell();
builder->get_CellFormat()->set_Width(100.0);
builder->Write(u"Row 2, Cell 1 Content");
builder->InsertCell();
builder->Write(u"Row 2, Cell 2 Content");
builder->InsertCell();
builder->get_CellFormat()->set_Width(200.0);
builder->Write(u"Row 2, Cell 3 Content.");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"WorkingWithTables.FormattedTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Cell> cell = builder->InsertCell();
builder->Writeln(u"Outer Table Cell 1");
builder->InsertCell();
builder->Writeln(u"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->get_FirstParagraph());
// Build the inner table.
builder->InsertCell();
builder->Writeln(u"Inner Table Cell 1");
builder->InsertCell();
builder->Writeln(u"Inner Table Cell 2");
builder->EndTable();
doc->Save(ArtifactsDir + u"WorkingWithTables.NestedTable.docx");
view raw nested-table.h hosted with ❤ by GitHub

通过DOM创建表(文档对象模型)

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<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.
auto table = MakeObject<Table>(doc);
doc->get_FirstSection()->get_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.
auto row = MakeObject<Row>(doc);
row->get_RowFormat()->set_AllowBreakAcrossPages(true);
table->AppendChild(row);
// We can now apply any auto fit settings.
table->AutoFit(AutoFitBehavior::FixedColumnWidths);
auto cell = MakeObject<Cell>(doc);
cell->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightBlue());
cell->get_CellFormat()->set_Width(80);
cell->AppendChild(MakeObject<Paragraph>(doc));
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"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->get_LastCell()->AppendChild(MakeObject<Paragraph>(doc));
row->get_LastCell()->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"Row 1, Cell 2 Text"));
doc->Save(ArtifactsDir + u"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-C.git.
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Note that AutoFitSettings does not apply to tables inserted from HTML.
builder->InsertHtml(String(u"<table>") + u"<tr>" + u"<td>Row 1, Cell 1</td>" + u"<td>Row 1, Cell 2</td>" + u"</tr>" + u"<tr>" +
u"<td>Row 2, Cell 2</td>" + u"<td>Row 2, Cell 2</td>" + u"</tr>" + u"</table>");
doc->Save(ArtifactsDir + u"WorkingWithTables.InsertTableFromHtml.docx");

插入现有表的副本

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Clone the table and insert it into the document after the original.
auto tableClone = System::ExplicitCast<Table>(table->Clone(true));
table->get_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->get_ParentNode()->InsertAfter(MakeObject<Paragraph>(doc), table);
doc->Save(ArtifactsDir + u"WorkingWithTables.CloneCompleteTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
auto clonedRow = System::ExplicitCast<Row>(table->get_LastRow()->Clone(true));
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
for (const auto& cell : System::IterateOver<Cell>(clonedRow->get_Cells()))
{
cell->RemoveAllChildren();
}
table->AppendChild(clonedRow);
doc->Save(ArtifactsDir + u"WorkingWithTables.CloneLastRow.docx");

如果您正在考虑在文档中创建与数据源中的每条记录一起动态增长的表,则不建议使用上述方法。 相反,通过使用带有区域的Mail merge更容易实现所需的输出。 你可以在 Mail Merge与区域 节。

比较创建表的方法

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

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

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