Search code examples
c#excelopenxml

Excel Internals: How to find the index of a Column?


I am trying to determine the Style of each column, in order to apply it to the data that is inserted in each cell.

The confusing part is that instead of an index, the Column class provides a Min and a Max value. Sometimes they are the same, sometimes they are 1 unit apart.

What is the deal with that Min-Max?

TIA

Worksheet worksheet = worksheetPart.Worksheet;
Columns   columns   = worksheet.GetFirstChild<Columns>();

for (Column column = (Column) columns.FirstChild; column != null; column = (Column) column.NextSibling())
{
    UInt32 Style;

    if (column.Style == null)
    {
        Style = 0;
    }
    else
    {
        Style = column.Style.Value;
    }
    var Min = column.Min.Value;
    var Max = column.Max.Value;
    Console.WriteLine("Column Min=" + Min + ", Max=" + Max + ", Style: " + Style);
}

Solution

  • It turns out that each so-called Column is in reality an aggregation of physical columns. When consecutive columns have the same characteristics, they are internally combined into one.

    The code below shows how to iterate through them and retrieve their Style:

    private Dictionary<char, UInt32> ColumnStyles(Worksheet worksheet)
    {
        Columns columns = worksheet.GetFirstChild<Columns>();
    
        char colIndex = 'A';
        for (Column column = (Column)columns.FirstChild; column != null; column = (Column)column.NextSibling())
        {
            UInt32 Min   = column.Min.Value;
            UInt32 Max   = column.Max.Value;
            UInt32 Style = column.Style.Value;
    
            for (int i = 1; i <= Max - Min + 1; i++)
            {
                StyleOf[colIndex++] = Style;
            }
        }
    
        return StyleOf;
    }