Search code examples
c#.netexcelepplus

Iterating and adding all column names to a ComboBox using EPPlus


I need to add the column names within a sheet to a combobox

I have tried the following

 var pck = new OfficeOpenXml.ExcelPackage();
            pck.Load(new System.IO.FileInfo("test.xlsx").OpenRead());
            var ws = pck.Workbook.Worksheets[1];

            int totalCols = ws.Dimension.End.Column;

            for (int i = 1; i <= totalCols; i++)
            {
              comboBox1.Items.Add(  (ws.Column(i).ToString()));
            }
        }

But this produces a Null Reference Exception.

Why is that happening?


Solution

  • Ensure that you're loading the package correctly and selecting the values correctly:

    // Select workbook
    var fileInfo = new FileInfo(@"yourfile.xlsx");
    
    // Load workbook
    using (var package = new ExcelPackage(fileInfo)) {
    // Itterate through workbook sheets
        foreach (var sheet in package.Workbook.Worksheets){
    // Itterate through each column until final column
            for (int i = 1; i <= sheet.Dimension.End.Column; i++) {
                comboBox1.Items.Add(sheet.Cells[1, i].Text);
            }
        }
    }
    

    This runs correctly in a new workbook with two sheets and values in the columns of each sheet.