Jun 19, 2012

Open Excel-.NET


Today I will explains how to open and read an Excel file through C#.We also use Microsoft Excel 14.0 Object Library in project as reference to open Excel files . 

Three Steps to Open Excel in .NET 
Step 1 Create a new project and Add Microsoft Excel 14.0 Object Library as reference.
Step 2 Add namespace: using Excel = Microsoft.Office.Interop.Excel.
Step 3 Add methods to open Excel

Check the Code samples below
//declare parts
Excel.Application myxlApp;
Excel.Workbook myxlWorkBook;
Excel.Worksheet myxlWorkSheet;
object misValue = System.Reflection.Missing.Value;
// Open Excel file
myxlApp = new Excel.Application();
myxlWorkBook = myxlApp.Workbooks.Open("D:\samples.xlsx", 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
myxlWorkSheet = (Excel.Worksheet)myxlWorkBook.Worksheets.get_Item(1);
// show Excel B1 Cell Contents.
MessageBox.Show(myxlWorkSheet.get_Range("B1", "B1").Value2.ToString());
//A good habit to close file and release object
myxlWorkBook.Close(true, misValue, misValue);
myxlApp.Quit();
releaseObject(myxlWorkSheet);
releaseObject(myxlWorkBook);
releaseObject(myxlApp);
//Note Release all object then show excel
System.Diagnostics.Process.Start("D:\1.xlsx");
// Exception handlers
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception exp)
{
obj = null;
MessageBox.Show("Fail to release the Object " + exp.ToString());
}
finally
{
GC.Collect();
}
}

No comments:

Post a Comment