Net-informations.com
SiteMap  | About    

How to open an Excel file in C#

The following section explains how to open and read an Excel file through C#.

For open or read an Excel file in C# , first you have to add the Microsoft Excel 12.0 Object Library in you project.

Create a new project and add a Command Button to the Form.

Form the following images you can find how to add Excel reference library in your project.

Select Reference Dialogue from Project menu

scsharp-excel-reference

Select Microsoft Excel 12.0 Object Library and click OK button

csharp-excel-library

Copy and paste the following source code in your C# project file.




using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());

            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        } 
    }
}

Note : You have to add Microsoft.Office.Interop.Excel to your source code.
using Excel = Microsoft.Office.Interop.Excel;

When you execute the C# source code , it will open the excel file and read the content in the cell A1


 CSharp Excel - Related Contents