Search code examples
c#.netvb.netepplus

Centering, Merging, and Wrapping Text In Cells - EPPlus


I'm trying to center a header(s) for an excel file like so: Excel Table

But I am missing a few details, since the code below one writes on one line and does not expand the cell's height. Here is my code so far:

ws.Cells[$"A{row}:F{row}"].Merge = true;
ws.Cells[$"A{row}"].Style.WrapText = true;
ws.SelectedRange[$"A{row}"].Value = purchaseHistory[0].LineText;

Solution

  • To center the merged cell both vertical and horizontally just do this:

    //Only need to grab the first cell of the merged range
    ws.Cells[$"A{row}"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
    ws.Cells[$"A{row}"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
    

    If you need to do something with the height of the rows you will want to look at the CustomHeight setting. This should explain it: Autofit rows in EPPlus