0

I'm having trouble figuring out how to import an excel file into an multidimensional array in c#. I'm not looking to do anything fancy, I just want simple excel first worksheet into an array in c#, and that's about it.

Thanks for all your help!

Jo Jo
  • 55
  • 1
  • 2
  • 4
  • Or if you don't want to use Office Interop - _[Reading Excel files from C#](http://stackoverflow.com/questions/15828/reading-excel-files-from-c-sharp?rq=1)_ –  Aug 30 '15 at 01:28
  • Please search before asking!! – Jeremy Thompson Aug 30 '15 at 01:36
  • the best method is using oledb and loading worksheet into a datatable which will give you the two dimensions. See following webpage : http://stackoverflow.com/questions/27579450/read-data-from-excel-using-oledb. I would use HDR = yes which will give you the first header row In excel as the column names. For complete set of connection strings see : http://www.connectionstrings.com/excel/ – jdweng Aug 30 '15 at 02:05

1 Answers1

2

You would be best to bring it into a datatable, in this code I am using closedXML which is available via nuget

public static DataTable ImportSheet(string fileName)
    {
        var datatable = new DataTable();
        var workbook = new XLWorkbook(fileName);
        var xlWorksheet = workbook.Worksheet(1);
        var range = xlWorksheet.Range(xlWorksheet.FirstCellUsed(), xlWorksheet.LastCellUsed());

        var col = range.ColumnCount();
        var row = range.RowCount();

        //if a datatable already exists, clear the existing table 
        datatable.Clear();
        for (var i = 1; i <= col; i++)
        {
            var column = xlWorksheet.Cell(1, i);
            datatable.Columns.Add(column.Value.ToString());
        }

        var firstHeadRow = 0;
        foreach (var item in range.Rows())
        {
            if (firstHeadRow != 0)
            {
                var array = new object[col];
                for (var y = 1; y <= col; y++)
                {
                    array[y - 1] = item.Cell(y).Value;
                }

                datatable.Rows.Add(array);
            }
            firstHeadRow++;
        }
        return datatable;
    }

This is working code, so all you'll need to do it copy and paste it, and call it using this code too

DataTable _dt = new DataTable();
_dt = ImportSheet(fileName);
Simon Price
  • 3,011
  • 3
  • 34
  • 98