How to Open and Read From Excel File in C#

How to Open and Read From Excel File in C#

First step is to add necessary references to the project.

1. Right click References and press Add References item in the menu.
2. Go to COM Tab and select Type Libraries.
3. Select the ticks of
    - Microsoft Excel 14.0 Object Library
    - Microsoft Office 14.0 Object Library

Required using statements:

using Microsoft.Office.Interop.Excel;

Here is the example code:

public void ReadExcelFile(String fileName)
{
    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);

    var app = new Application();
    var workbook = app.Workbooks.Open(path);

    if (workbook.Sheets.Count > 0)
    {
        var worksheet = workbook.Sheets[1];
        var range = worksheet.UsedRange;

        var numRows = range.Rows.Count;
        var numCols = range.Columns.Count;

        for (int j = 1; j < numRows; ++j)
            for (int i = 1; i < numCols; ++i)
                if (range.Cells[j, i].Value2 != null)
                    var data = (Double.Parse(range.Cells[j, i].Value2.ToString()));

        workbook.Close(true, null, null);
        app.Quit();

        ReleaseObject(worksheet);
        ReleaseObject(workbook);
        ReleaseObject(app);
    }
}

private void ReleaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        Console.WriteLine("Unable to release the Object {0}", ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}


added 4 years 4 months ago

Contents related to 'How to Open and Read From Excel File in C#'

How to Create and Write Excel File in C#: How to create an excel file and write in its cells using c#?

- Open a text file and read line by line in C#
- Convert.ToInt32() vs Int32.Parse() in C#
- How to C# Linq Group By by paramater/field names
- Simple Injector
- How to check memory consumption in c#
- How can I implement C/C++ "union" in C#?
- How to Open and Read From Excel File in C#
- Weak References
- Lazy Initialization
- Enable Nuget Package Restore
- OnixS FIX Engine
- Rapid Addition FIX API
- How to change DateTime format in C#
- How to change number decimal seperator in C#?
2
1