Independentsoft
Home
Purchase
Support
Company
Contact
Word .NET
>
Tutorial
> Horizontally merged cells
The following example shows you how to create horizontally merged table cells.
C# example
using System; using Independentsoft.Office.Word; using Independentsoft.Office.Word.Tables; namespace Sample { class Program { static void Main(string[] args) { WordDocument doc = new WordDocument(); Table table = new Table(StandardBorderStyle.SingleLine); table.Width = new Width(TableWidthUnit.Percent, 100); // First row - header cell spanning all 3 columns Run headerRun = new Run(); headerRun.AddText("Merged Header Cell (spans 3 columns)"); Paragraph headerPara = new Paragraph(); headerPara.Add(headerRun); Cell headerCell = new Cell(); headerCell.Add(headerPara); headerCell.GridSpan = 3; // span across 3 columns Row headerRow = new Row(); headerRow.Add(headerCell); // Second row - normal cells Cell cell1 = CreateCell("Column 1"); Cell cell2 = CreateCell("Column 2"); Cell cell3 = CreateCell("Column 3"); Row dataRow = new Row(); dataRow.Add(cell1); dataRow.Add(cell2); dataRow.Add(cell3); table.Add(headerRow); table.Add(dataRow); doc.Body.Add(table); doc.Save("c:\\test\\output.docx", true); } static Cell CreateCell(string text) { Run run = new Run(); run.AddText(text); Paragraph para = new Paragraph(); para.Add(run); Cell cell = new Cell(); cell.Add(para); return cell; } } }
VB example
Imports System Imports Independentsoft.Office.Word Imports Independentsoft.Office.Word.Tables Module Module1 Sub Main(ByVal args() As String) Dim doc As WordDocument = New WordDocument() Dim table As Table = New Table(StandardBorderStyle.SingleLine) table.Width = New Width(TableWidthUnit.Percent, 100) ' First row - header cell spanning all 3 columns Dim headerRun As Run = New Run() headerRun.AddText("Merged Header Cell (spans 3 columns)") Dim headerPara As Paragraph = New Paragraph() headerPara.Add(headerRun) Dim headerCell As Cell = New Cell() headerCell.Add(headerPara) headerCell.GridSpan = 3 ' span across 3 columns Dim headerRow As Row = New Row() headerRow.Add(headerCell) ' Second row - normal cells Dim cell1 As Cell = CreateCell("Column 1") Dim cell2 As Cell = CreateCell("Column 2") Dim cell3 As Cell = CreateCell("Column 3") Dim dataRow As Row = New Row() dataRow.Add(cell1) dataRow.Add(cell2) dataRow.Add(cell3) table.Add(headerRow) table.Add(dataRow) doc.Body.Add(table) doc.Save("c:\test\output.docx", True) End Sub Private Function CreateCell(ByVal text As String) As Cell Dim run As Run = New Run() run.AddText(text) Dim para As Paragraph = New Paragraph() para.Add(run) Dim cell As Cell = New Cell() cell.Add(para) Return cell End Function End Module
Need help? Ask our developers:
Name*
Email*
Message*