Joining and Splitting Tables
A table which is represented in the Aspose.Words Document Object Model is made up of independent rows and cells which makes joining or splitting tables easy. In order to manipulate a table to split or join with another table we simply need to move the rows from one table to another.
Combining Two Tables into One
The rows from the second table simply need to be shifted to the end of the first table and the container of the second table deleted. Below example shows how to combine the rows from two tables into one.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// Load the document. | |
Document doc = new Document(dataDir + fileName); | |
// Get the first and second table in the document. | |
// The rows from the second table will be appended to the end of the first table. | |
Table firstTable = (Table)doc.GetChild(NodeType.Table, 0, true); | |
Table secondTable = (Table)doc.GetChild(NodeType.Table, 1, true); | |
// Append all rows from the current table to the next. | |
// Due to the design of tables even tables with different cell count and widths can be joined into one table. | |
while (secondTable.HasChildNodes) | |
firstTable.Rows.Add(secondTable.FirstRow); | |
// Remove the empty table container. | |
secondTable.Remove(); | |
dataDir = dataDir + "Table.CombineTables_out.doc"; | |
// Save the finished document. | |
doc.Save(dataDir); |
Split a Table into Two Separate Tables
We first need to pick a row at where to split the table. Once we know this we can create two tables from the original table by following these simple steps:
- Create a clone of the table without cloning children to hold the moved rows and insert it after the original table.
- Starting from the specified row move all subsequent rows to this second table.
Below example shows how to split a table into two tables a specific row.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// Load the document. | |
Document doc = new Document(dataDir + fileName); | |
// Get the first table in the document. | |
Table firstTable = (Table)doc.GetChild(NodeType.Table, 0, true); | |
// We will split the table at the third row (inclusive). | |
Row row = firstTable.Rows[2]; | |
// Create a new container for the split table. | |
Table table = (Table)firstTable.Clone(false); | |
// Insert the container after the original. | |
firstTable.ParentNode.InsertAfter(table, firstTable); | |
// Add a buffer paragraph to ensure the tables stay apart. | |
firstTable.ParentNode.InsertAfter(new Paragraph(doc), firstTable); | |
Row currentRow; | |
do | |
{ | |
currentRow = firstTable.LastRow; | |
table.PrependChild(currentRow); | |
} | |
while (currentRow != row); | |
dataDir = dataDir + "Table.SplitTable_out.doc"; | |
// Save the finished document. | |
doc.Save(dataDir); |