创建表

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

默认表样式

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

表属性 Aspose.Words中的默认值
Border Style Single
Border Width 1/2 pt
边框颜色 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-Java.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(getArtifactsDir() + "WorkingWithTables.CreateSimpleTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.setLeftIndent(20.0);
// Set height and define the height rule for the header row.
builder.getRowFormat().setHeight(40.0);
builder.getRowFormat().setHeightRule(HeightRule.AT_LEAST);
builder.getCellFormat().getShading().setBackgroundPatternColor(new Color((198), (217), (241)));
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
builder.getFont().setSize(16.0);
builder.getFont().setName("Arial");
builder.getFont().setBold(true);
builder.getCellFormat().setWidth(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.getCellFormat().setWidth(200.0);
builder.write("Header Row,\n Cell 3");
builder.endRow();
builder.getCellFormat().getShading().setBackgroundPatternColor(Color.WHITE);
builder.getCellFormat().setWidth(100.0);
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
// Reset height and define a different height rule for table body.
builder.getRowFormat().setHeight(30.0);
builder.getRowFormat().setHeightRule(HeightRule.AUTO);
builder.insertCell();
// Reset font formatting.
builder.getFont().setSize(12.0);
builder.getFont().setBold(false);
builder.write("Row 1, Cell 1 Content");
builder.insertCell();
builder.write("Row 1, Cell 2 Content");
builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 1, Cell 3 Content");
builder.endRow();
builder.insertCell();
builder.getCellFormat().setWidth(100.0);
builder.write("Row 2, Cell 1 Content");
builder.insertCell();
builder.write("Row 2, Cell 2 Content");
builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 2, Cell 3 Content.");
builder.endRow();
builder.endTable();
doc.save(getArtifactsDir() + "WorkingWithTables.FormattedTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.getFirstParagraph());
// Build the inner table.
builder.insertCell();
builder.writeln("Inner Table Cell 1");
builder.insertCell();
builder.writeln("Inner Table Cell 2");
builder.endTable();
doc.save(getArtifactsDir() + "WorkingWithTables.NestedTable.docx");

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

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.getFirstSection().getBody().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.getRowFormat().setAllowBreakAcrossPages(true);
table.appendChild(row);
// We can now apply any auto fit settings.
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
Cell cell = new Cell(doc);
cell.getCellFormat().getShading().setBackgroundPatternColor(Color.BLUE);
cell.getCellFormat().setWidth(80.0);
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().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.deepClone(false));
row.getLastCell().appendChild(new Paragraph(doc));
row.getLastCell().getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 2 Text"));
doc.save(getArtifactsDir() + "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-Java.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(getArtifactsDir() + "WorkingWithTables.InsertTableFromHtml.docx");

插入现有表的副本

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "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.deepClone(true);
table.getParentNode().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.getParentNode().insertAfter(new Paragraph(doc), table);
doc.save(getArtifactsDir() + "WorkingWithTables.CloneCompleteTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
Row clonedRow = (Row) table.getLastRow().deepClone(true);
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
for (Cell cell : (Iterable<Cell>) clonedRow.getCells())
cell.removeAllChildren();
table.appendChild(clonedRow);
doc.save(getArtifactsDir() + "WorkingWithTables.CloneLastRow.docx");

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

比较创建表的方法

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

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

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