In DsWord, a cell element is represented by the Cell class which allows you to access each cell of a table which can be added through Add method of the CellCollection class.
Each element of a table, such as row, column, and cell, can have different styles and formatting. DsWord allows you to set the table cell formatting using Format property of the Cell class along with the CellFormat class properties. It also lets you merge cells, both vertically and horizontally, in a table. The VerticalMerge property allows a cell to merge vertically with the other cells in a table. Similarly, the HorizontalMerge property allows a cell to merge horizontally with the other cells in a table.
To set cell formatting in a table:
C# |
Copy Code |
---|---|
//Load the document and access the table doc.Load("CreateTable.docx"); Table t = doc.Body.Sections.First.GetRange().Tables[0]; //Set cell formatting t.Rows[0].Cells[2].Format.TextFlowDirection = TextFlowDirection.TopToBottomRightToLeft; t.Rows[0].Cells[2].Format.Padding.Top = t.Rows[0].Cells[2].Format.Padding.Bottom = 2; //Save the document doc.Save("SetCellFormatting.docx"); |
To get formatting of a cell from a table in an existing document:
C# |
Copy Code |
---|---|
//Load the document and access the table doc.Load("SetCellFormatting.docx"); Table t = doc.Body.Sections.First.GetRange().Tables[0]; //Get cell padding of the third cell in the first row CellFormat cformat = t.Rows[0].Cells[2].Format; float paddingTop = cformat.Padding.Top; //Write the fetched padding on the console Console.WriteLine("Top Padding: " + paddingTop); |
To merge cells horizontally in a table:
C# |
Copy Code |
---|---|
//Load the document and access the table doc.Load("CreateTable.docx"); Table t = doc.Body.Sections.First.GetRange().Tables[0]; // Set up cell (1,1) to visually span two following cells, hence merge the cells t.Rows[1].Cells[1].Format.GridSpan = 3; // Remove the 2 following cells (unless we want to create a jagged table) t.Rows[1].Cells[3].Delete(); t.Rows[1].Cells[2].Delete(); //Save the document doc.Save("MergedCells.docx"); |
To insert a graphic element, such as an image, in a table cell:
C# |
Copy Code |
---|---|
doc.Load("CreateTable.docx"); //Access the table Table t = doc.Body.Sections.First.GetRange().Tables[0]; // Load picture data var picBytes = File.ReadAllBytes(Path.Combine("Resources", "Images", "road.jpg")); // Add picture, specifying its mime type: var pic = t.Rows.Last.Cells.Last.GetRange().Runs.First.GetRange().Pictures.Add( picBytes, "image/jpeg"); // Picture size pic.Size.Width.Value = 200; pic.Size.Height.Value = 100; //Allow automatic resizing of the cell t.Format.AllowAutoFit = true; //Save the document doc.Save("InsertGraphicElement.docx"); |
For more information about implementation of cells using DsWord, see DsWord sample browser.