Patrick
Patrick

Reputation: 2781

Unable to center text with the C# lib ClosedXML

I am trying to center text with the MVC lib ClosedXML but it only works when the cell has a background color set and I want to set the alignment without it:

var workbook = new XLWorkbook("c:\\temp\\file.xlsx");
var worksheet = workbook.Worksheet("Sheet");

worksheet .Cell(1, 1).Style.Fill.BackgroundColor = XLColor.White; // without this line it doe not work
worksheet.Cell(1, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

Upvotes: 4

Views: 18423

Answers (3)

Safee
Safee

Reputation: 88

The solution provided by mcalex works well for a particular cell. However, if you want to center align whole worksheet, you can use the following code:

ws.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

Upvotes: 4

New Watcharapon
New Watcharapon

Reputation: 11

ws.Cell(row, Column).Value = "Alignment top"; ws.Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top)

Upvotes: 1

mcalex
mcalex

Reputation: 6778

This works for me:

worksheet.Cell(1, 1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

but as far as I know it's just a wrapper around ...Horizontal = XLAlignmentHorizontalValues.Center

Upvotes: 16

Related Questions