Read Excel First Column using C# into Array

Brantley Blanchard picture Brantley Blanchard · Dec 14, 2012 · Viewed 44.8k times · Source

I'm trying to read in the values of the first column into an array. What's the best way to do that? Below is the code I have so far. Basically I'm trying to get the range of data for that column so I can pull the cell values into a system array.

Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

if (xlsApp == null)
{
    Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
    return null;
}

//xlsApp.Visible = true;

Workbook wb = xlsApp.Workbooks.Open(filename, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = wb.Worksheets;
Worksheet ws = (Worksheet)sheets.get_Item(1);

//***Breaks Here***
ListColumn column = ws.ListObjects[1].ListColumns[1];
Range range = column.DataBodyRange;
System.Array myvalues = (System.Array)range.Cells.Value;

Answer

Brantley Blanchard picture Brantley Blanchard · Dec 14, 2012

Here is what I ended up using to get it to work. Once you know that Columns actually returns a range, storing it that way seems to compile and run fine. Here is the working method in my ExcelReader class. I plan to use this for test driven data on WebDriver.

    public static string[] FirstColumn(string filename)
    {
        Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlsApp == null)
        {
            Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
            return null;
        }

        //Displays Excel so you can see what is happening
        //xlsApp.Visible = true;

        Workbook wb = xlsApp.Workbooks.Open(filename,
            0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
        Sheets sheets = wb.Worksheets;
        Worksheet ws = (Worksheet)sheets.get_Item(1);

        Range firstColumn = ws.UsedRange.Columns[1];
        System.Array myvalues = (System.Array)firstColumn.Cells.Value;
        string[] strArray = myvalues.OfType<object>().Select(o => o.ToString()).ToArray(); 
        return strArray;
    }