Monday, October 3, 2011

Excel reading through Microsoft Excel 11.0 Object Library in c#

Use Below Code:

using Microsoft.Office.Interop.Excel;

string Path = @"c:\test.xls";
         // initialize the Excel Application class
            Microsoft.Office.Interop.Excel.ApplicationClass app = new ApplicationClass();


        // create the workbook object by opening the excel file.
            Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(Path,
                                                      0,
                                                      true,
                                                      5,
                                                      "",
                                                      "",
                                                      true,
                                                      Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
                                                      "\t",
                                                      false,
                                                      false,
                                                      0,
                                                      true,
                                                      1,
                                                      0);
         // get the active worksheet using sheet name or active sheet
            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;


         int index = 0;


         // This row,column index should be changed as per your need.
         // i.e. which cell in the excel you are interesting to read.
         object rowIndex = 2;
         object colIndex1 = 1;
         object colIndex2 = 2;


         try
         {


             while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
            {
               rowIndex = 2+index;
               string firstName = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2.ToString();
               string lastName = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, colIndex2]).Value2.ToString();
               MessageBox.Show(firstName+"    "+lastName);


              index++;


           }
         }
         catch(Exception ex)
         {
            app.Quit();
            Console.WriteLine(ex.Message);
         }

Copy from this  http://www.codeproject.com/KB/cs/Excel_Application_in_C_.aspx

No comments:

Post a Comment