Search code examples
officewriter

Cell Alignment using ExcelApplication


I am using ExcelApplication, not ExcelTemplate - so I'm programmatically doing a slight bit of formatting so it's just a super plain excel sheet - however, I presume my end-user would like to do formatting on their own so I'm keeping it light.

My header row is larger than other rows by measure of height:

        foreach (Worksheet ws in book)
        {
            ws.GetRowProperties(0).Height = 25; // this works
            ws.GetRowProperties(0).Style.VerticalAlignment = Style.VAlign.Center; // this has no effect
        }

I have attempted to apply cell alignment in several different ways by now, and I can't seem to ever have an end result. Any ideas?


Solution

  • I have dealt with this by creating an Area and then Applying a style to said Area:

    Area headerArea;
    Style headerAreaStyle = book.CreateStyle();
    headerAreaStyle.VerticalAlignment = Style.VAlign.Center;
    headerAreaStyle.HorizontalAlignment = Style.HAlign.Center;
    headerAreaStyle.Font.Size = 13;
    
    foreach (Worksheet ws in book)
    {
        switch (ws.Name)
        {
            case ("First Sheet"):
                headerArea = ws.CreateArea(0, 0, 1, 2);
                headerArea.SetRowHeight(0, 20);
                headerArea.ApplyStyle(headerAreaStyle);
                break;
            case ("Second Sheet"):
                headerArea = ws.CreateArea(0, 0, 1, 5);
                headerArea.SetRowHeight(0, 20);
                headerArea.ApplyStyle(headerAreaStyle);
                break;
            case ("Third Sheet"):
                headerArea = ws.CreateArea(0, 0, 1, 3);
                headerArea.SetRowHeight(0, 20);
                headerArea.ApplyStyle(headerAreaStyle);
                break;
            case ("Fourth Sheet"):
                headerArea = ws.CreateArea(0, 0, 1, 3);
                headerArea.SetRowHeight(0, 20);
                headerArea.ApplyStyle(headerAreaStyle);
                break;
            default:
                break;
        }
    }
    

    I'm sure there are other -- and better -- ways to do this, but it works just fine for me.

    Note that the Switch here is completely irrelevant to anyone but me. There are ways of doing in a more dynamic fashion, but these exports are static in terms of column numbers.