Merge Rows and Cells in Table using C# and .NET


How to create a new table with rows and cells merged by vertical (rowspan) and horizontal (colspan).

Complete code


using System.IO;
using System.Linq;
using SautinSoft.Document;
using SautinSoft.Document.Tables;

namespace Sample
{
    class Sample
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            MergeRowsAndCellsInTable();
        }

        /// <summary>
        /// Create a new table with rows and cells merged by vertical (rowspan) and horizontal (colspan).
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/table-with-merged-rows-and-cells.php
        /// </remarks>
        public static void MergeRowsAndCellsInTable()
        {

            DocumentCore dc = new DocumentCore();

            Table table = new Table(dc,
                   new TableRow(dc,
                            new TableCell(dc, new Paragraph(dc, "Cell 1-1")),
                            new TableCell(dc, new Paragraph(dc, "Cell 1-2")),
                            new TableCell(dc, new Paragraph(dc, "Cell 1-3")),
                            new TableCell(dc, new Paragraph(dc, "Cell 1-4"))),
                   
                   new TableRow(dc,
                            new TableCell(dc, new Paragraph(dc, "Cell 2-1 -> 3-2"))
                            {
                                RowSpan = 2,
                                ColumnSpan = 2
                            },
                            new TableCell(dc, new Paragraph(dc, "Cell 2-3 -> 2-4"))
                            {
                                ColumnSpan = 2
                            }),
                   
                   new TableRow(dc,
                            new TableCell(dc) { ColumnSpan = 2 },
                            new TableCell(dc, new Paragraph(dc, "Cell 3-3")),
                            new TableCell(dc, new Paragraph(dc, "Cell 3-4"))),
                   
                   new TableRow(dc,
                            new TableCell(dc, new Paragraph(dc, "Cell 4-1"))),
                   new TableRow(dc,
                            new TableCell(dc, new Paragraph(dc, "Cell 5-1"))));

            table.TableFormat.DefaultCellPadding = new Padding(10, LengthUnit.Pixel);

            // Set the table width to 10 cm and convert it to points.
            double tableWidthInPoints = LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point);
            table.TableFormat.PreferredWidth = new TableWidth(tableWidthInPoints, TableWidthUnit.Point);
            for (int r = 0; r < table.Rows.Count; r++)
            {
                for (int c = 0; c < table.Rows[r].Cells.Count; c++)
                {
                    TableCell cell = table.Rows[r].Cells[c];
                    cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Dashed, Color.Black, 1);
                    cell.CellFormat.BackgroundColor = new Color("#FFCC00");
                }
            }

            dc.Sections.Add(new Section(dc, table));

            dc.Save("MergedTableCells.docx");
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("MergedTableCells.docx") { UseShellExecute = true });
        }
    }
}

Download

Imports System.IO
Imports System.Linq
Imports SautinSoft.Document
Imports SautinSoft.Document.Tables

Namespace Sample
    Friend Class Sample
        Shared Sub Main(ByVal args() As String)
            MergeRowsAndCellsInTable()
        End Sub
        ''' Get your free 30-day key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Create a new table with rows and cells merged by vertical (rowspan) and horizontal (colspan).
        ''' </summary>
        ''' <remarks>
        ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/table-with-merged-rows-and-cells.php
        ''' </remarks>
        Public Shared Sub MergeRowsAndCellsInTable()

            Dim dc As New DocumentCore()

            Dim table As Table = New Table(dc,
                 New TableRow(dc,
                         New TableCell(dc, New Paragraph(dc, "Cell 1-1")),
                         New TableCell(dc, New Paragraph(dc, "Cell 1-2")),
                         New TableCell(dc, New Paragraph(dc, "Cell 1-3")),
                         New TableCell(dc, New Paragraph(dc, "Cell 1-4"))),
                 New TableRow(dc,
                         New TableCell(dc, New Paragraph(dc, "Cell 2-1 -> 3-2")) With
                {
                .RowSpan = 2,
                .ColumnSpan = 2
                },
                         New TableCell(dc, New Paragraph(dc, "Cell 2-3 -> 2-4")) With
                {.ColumnSpan = 2}),
                New TableRow(dc,
                         New TableCell(dc) With
                {.ColumnSpan = 2},
                         New TableCell(dc, New Paragraph(dc, "Cell 3-3")),
                         New TableCell(dc, New Paragraph(dc, "Cell 3-4"))),
                New TableRow(dc, New TableCell(dc, New Paragraph(dc, "Cell 4-1"))),
                New TableRow(dc, New TableCell(dc, New Paragraph(dc, "Cell 5-1"))))

            table.TableFormat.DefaultCellPadding = New Padding(10, LengthUnit.Pixel)

            ' Set the table width to 10 cm and convert it to points.
            Dim tableWidthInPoints As Double = LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point)
            table.TableFormat.PreferredWidth = New TableWidth(tableWidthInPoints, TableWidthUnit.Point)
            For r As Integer = 0 To table.Rows.Count - 1
                Dim c As Integer = 0
                Do While c < table.Rows(r).Cells.Count
                    Dim cell As TableCell = table.Rows(r).Cells(c)
                    cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Dashed, Color.Black, 1)
                    cell.CellFormat.BackgroundColor = New Color("#FFCC00")
                    c += 1
                Loop
            Next r

            dc.Sections.Add(New Section(dc, table))

            dc.Save("MergedTableCells.docx")
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("MergedTableCells.docx") With {.UseShellExecute = True})
        End Sub
    End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.