34

I am having an issue getting a range of merged cells to horizontal align centered. The alignment stays as left. Here's my code.

ws.Cells[lStartColumn + lStartRow].Value = gPortfolioName + " - " + lTypeOfPortfolioPerf + " Performance Update";
ws.Cells[lStartColumn + lStartRow + ":" + lEndColumn + lEndRow].Merge = true;
ws.Cells[lStartColumn + lStartRow + ":" + lEndColumn + lEndRow].Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous;
ws.Cells[lStartColumn + lStartRow + ":" + lEndColumn + lEndRow].Style.Font.Size = 14;
ws.Cells[lStartColumn + lStartRow + ":" + lEndColumn + lEndRow].Style.Font.Color.SetColor(bgTitleColor);
ws.Cells[lStartColumn + lStartRow + ":" + lEndColumn + lEndRow].Style.Font.Bold = true;
Simple Sandman
  • 900
  • 3
  • 11
  • 34
David Choi
  • 6,131
  • 10
  • 28
  • 28

2 Answers2

66

Should be:

worksheet.Cells["A2:A4"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

But I think you should be doing it last, as some styling changes can affect your alignment. The order matters.

Simple Sandman
  • 900
  • 3
  • 11
  • 34
davidahines
  • 3,976
  • 16
  • 53
  • 87
8

Center align merged cells

 // ws.Cells[Rowstart, ColStart, RowEnd, ColEnd]

  ws.Cells[1, 1].Value = "BILL OF MATERIALS";
  ws.Cells[1, 1, 1, 7].Merge = true; //Merge columns start and end range
  ws.Cells[1, 1, 1, 7].Style.Font.Bold = true; //Font should be bold
  ws.Cells[1, 1, 1, 7].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // Alignment is center
  ws.Cells[1, 1, 1, 7].Style.Font.Size = 25;
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87