Excel file open in wpf c#

Open Excel file in WPF C#


Now to easy to open excel file in wpf

Project -> Add Reference menu item. Go to the .NET tab of the dialog box that pops up and scroll down the Microsoft.Office.Interop.Excel

using Excel = Microsoft.Office.Interop.Excel;

Now Open file Dialog to select excel file and get value from excel file.

private void button1_Click(object sender, RoutedEventArgs e)
{
  Excel.Application xlApp;
  Excel.Workbook xlWorkBook;
  Excel.Worksheet xlWorkSheet;
  Excel.Range range;

  string str;
  int rCnt = 0;
  int cCnt = 0;
  int cCnt2 = 0;
  OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
  OpenFileDialog1.Filter = "Excel files (*.xls)|*.xls;";
  OpenFileDialog1.ShowDialog();
  if (OpenFileDialog1.FileName != String.Empty)
  {
     xlApp = new Excel.Application();
     xlWorkBook = xlApp.Workbooks.Open(OpenFileDialog1.FileName, 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);
     range = xlWorkSheet.UsedRange;
     cCnt = 1;
     cCnt2 = 2;
        for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
        {
           for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
           {
              str = Convert.ToString((range.Cells[rCnt, cCnt] as Excel.Range).Value2);
              MessageBox.Show(str);
           }
        }
      xlWorkBook.Close(true, null, null);
      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();
  }
}

Download Code
Excel file open in wpf c# Excel file open in wpf c# Reviewed by Bhaumik Patel on 9:27 PM Rating: 5