Articles in this section
Category / Section

How to split a table in a Word document using a bookmark between rows

6 mins read

Syncfusion® Essential® DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can split a table in a Word document using a bookmark between rows using C#.

To achieve this, follow the steps below:

  • Open the Word document containing the table.
  • Find all bookmarks within the table cells.
  • Identify the start and end rows for splitting, based on each bookmark.
  • Split the table from the start row to the end row.
  • Each newly split table is inserted correctly in the sequence.
  • Save the modified Word document.

Steps to split a table in a Word document using a bookmark between rows:

  1. Create a new .NET Core console application project. Create console application in Visual Studio
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
    Add DocIO NuGet package reference to the project

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without trail message.

  1. Include the following namespaces in Program.cs file
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using System.Collections.Generic;
using System.IO; 
  1. Use the following code example to split a table in a Word document using a bookmark between rows.
    C#
using (FileStream fileStreamPath = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
   //Open an existing Word document.
   using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx))
   {
       //Get all the bookmarkstart in the cell.
       //If bookmark mentioned anywhere in table "tr" in file level, DocIO parsed inside cell only.
       List<Entity> bookmarkStart = document.FindAllItemsByProperty(EntityType.BookmarkStart, "OwnerParagraph.IsInCell", true.ToString());
       //Find start and end row based on bookmark start.
       //Then split the table.
       for (int i = 0; i < bookmarkStart.Count; i++)
       {
           BookmarkStart start = bookmarkStart[i] as BookmarkStart;
           WTableRow startRow = GetOwnerRow(start);
           WTable table = startRow.Owner as WTable;
           WTableRow endRow;

           #region Find start and end row to split based on bookmark start
           //If there is any bookmark start further in table,
           //then get previous row of bookmark start.
           if (i < bookmarkStart.Count - 1)
           {
               //Get the owner row of next bookmark start.
               WTableRow ownerRow = GetOwnerRow(bookmarkStart[i + 1] as BookmarkStart);
               //Get the previous row.
               endRow = ownerRow.PreviousSibling as WTableRow;
           }
           //If there is no further bookmark start in table, consider last row as end of splitted table.
           else
               endRow = (startRow.Owner as WTable).LastRow;
           #endregion

           #region Split table
           //Split the table from start row to end row.
           WTable splittedTable = SplitTable(table, startRow.GetRowIndex(), endRow.GetRowIndex());
           //Get the owner of table.
           WTextBody ownerBody = table.OwnerTextBody;
           int indexToInsert = ownerBody.ChildEntities.IndexOf(table) + i * 2 + 1;
           //Insert paragraph to differentiate two tables.
           //As per Microsoft Word behavior, if two tables without any paragraph between them, it will be treated as one table.
           WParagraph paragraph = new WParagraph(document);
           ownerBody.ChildEntities.Insert(indexToInsert, paragraph);
           //Add splitted table, next to the paragraph.
           indexToInsert++;
           ownerBody.ChildEntities.Insert(indexToInsert, splittedTable);
           #endregion
       }
       //Create file stream.
       using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Output.docx"), FileMode.Create, FileAccess.ReadWrite))
       {
           //Save the Word document to file stream.
           document.Save(outputFileStream, FormatType.Docx);
       }
   }
}
  1. Use the following helper method to get the owner row of bookmark start.
    C#
/// <summary>
/// Get the owner row of bookmark start.
/// </summary>
static WTableRow GetOwnerRow(BookmarkStart bookmarkStart)
{
   if (bookmarkStart.OwnerParagraph.IsInCell)
   {
       return (bookmarkStart.OwnerParagraph.OwnerTextBody as WTableCell).OwnerRow;
   }
   return null;
}
  1. Use the following helper method to split a table from the bookmark’s start row to the end row.
    C#
/// <summary>
/// Split a table from the bookmarks start row to the end row.
/// </summary>
static WTable SplitTable(WTable table, int rowStartIndex, int rowEndIndex)
{
   //Clone the table.
   WTable clonedTable = table.Clone();
   //Table should have atleast 1 row and 1 cell.
   clonedTable.ResetCells(1, 1);
   
   //Clone the rows from owner table to new table one by one.
   for (int i = rowStartIndex; i <= rowEndIndex; i++)
   {
       clonedTable.Rows.Add(table.Rows[i].Clone());
   }
   //Remove the first row from cloned table.
   clonedTable.Rows.RemoveAt(0);
   
   //Delete those row from owner table.
   for (int i = rowEndIndex; i >= rowStartIndex; i--)
   {
       table.Rows.RemoveAt(i);
   }
   return clonedTable;
}

You can download a complete working sample to split a table in a Word document using a bookmark between rows from the GitHub.

By executing the program, you will get the Word document as follows.

Output Word document

Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Conclusion

I hope you enjoyed learning how to replace the table cell content in .NET Core Word document.

You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied