How to: Align Cell Content
- 3 minutes to read
To align data contained within a cell, use the properties of the Alignment object.
To change the alignment attributes for a range of cells, call the CellRange.BeginUpdateFormatting method for this range, use the Alignment property of the returned Formatting object to access and modify the Alignment object, and call the CellRange.EndUpdateFormatting method to finalize the modification.
The Alignment object provides the following properties to change cell alignment settings:
- Alignment.Horizontal, Alignment.Vertical - set the horizontal and vertical position of cell content.
- Alignment.Indent - sets the indentation of cell content.
- Alignment.WrapText - sets whether or not text should wrap in a cell.
- Alignment.ShrinkToFit - sets whether or not text should shrink to fit cell size.
- Alignment.RotationAngle - sets the rotation of text within a cell.
To share alignment settings with multiple cells in a single step, create or modify the style with the Formatting.Alignment property specified as required, and assign this style to CellRange.Style for the desired cells.
Cell cellA1 = worksheet.Cells["A1"]; cellA1.Value = "Right and top"; cellA1.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Right; cellA1.Alignment.Vertical = SpreadsheetVerticalAlignment.Top; Cell cellA2 = worksheet.Cells["A2"]; cellA2.Value = "Center"; cellA2.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center; cellA2.Alignment.Vertical = SpreadsheetVerticalAlignment.Center; Cell cellA3 = worksheet.Cells["A3"]; cellA3.Value = "Left and bottom, indent"; cellA3.Alignment.Indent = 1; Cell cellB1 = worksheet.Cells["B1"]; cellB1.Value = "The Alignment.ShrinkToFit property is applied"; cellB1.Alignment.ShrinkToFit = true; Cell cellB2 = worksheet.Cells["B2"]; cellB2.Value = "Rotated Cell Contents"; cellB2.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center; cellB2.Alignment.Vertical = SpreadsheetVerticalAlignment.Center; cellB2.Alignment.RotationAngle = 15; Cell cellB3 = worksheet.Cells["B3"]; cellB3.Value = "The Alignment.WrapText property is applied to wrap the text within a cell"; cellB3.Alignment.WrapText = true;
The image below shows how text can be aligned within worksheet cells (the workbook is opened in Microsoft® Excel®).