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!

3
  • Or if you don't want to use Office Interop - Reading Excel files from C# Commented Aug 30, 2015 at 1:28
  • Please search before asking!! Commented Aug 30, 2015 at 1:36
  • the best method is using oledb and loading worksheet into a datatable which will give you the two dimensions. See following webpage : stackoverflow.com/questions/27579450/…. 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 : connectionstrings.com/excel Commented Aug 30, 2015 at 2:05

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

XLWorkbook is not in interloop service?
@Faisal this is using ClosedXML, what is the actual question and do you have an issue that requires a new question?
no I am getting an error on XLWorkbook
did you grab ClosedXML from nuget?
If youre having an issue, create a new question, send me the link and I will try to help you.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.