Reading an Excel file in C#

Hello experts:
I'm trying to load the load test.xls contents thru c# code so that I can update some data base fields:
My code is below:

public class BankParserClass

Excel.Application excelApp = new Excel.ApplicationClass();

Excel.Workbook newWorkbook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
( this line of code gets an error    here on excelApp : denotes a fileld where a class is expected)                                                  

string workbookPath = "c:/test.xls";
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
      0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
      true, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
      string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
Excel.Range excelCell =(Excel.Range)excelWorksheet.get_Range("A1", "A1");

I got other errors but I think they are related to the 1st error above.  

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

have you added a reference to your application? I mean "Microsoft Excell 9.0 (or 10.0) Object Library"?

Hi  lancerxe,

This is application is kind of test application which tells how to use Microsoft Excel 10.0 Object Library, by using this library, how to load/read the excel contents.

Note: Here, I have created test.xls file which will be copied to c:\ before run the application.

Application developed using sample console application under VC# projects.


 1. Include the following reference into the project :

  Microsoft Excel 10.0 Object Library

  Microsoft Office 10.0 Object Library


2. Include the name space i.e. using Excel.

3. Creating the ExcelApplicationClass,WorkBook and Range.

Find the complete code below:

using System;
using Excel;
namespace TestExcel
 /// <summary>
 /// Summary description for ExcelApplication.
 /// </summary>
 class ExcelApplication
      /// <summary>
  /// The main entry point for the application.
  /// </summary>
      static void Main(string[] args)
         string Path = @"c:\test.xls";
         // initialize the Excel Application class
         Excel.ApplicationClass app = new ApplicationClass();
         // create the workbook object by opening the excel file.
         Excel.Workbook workBook = app.Workbooks.Open(Path,
         // get the active worksheet using sheet name or active sheet
         Excel.Worksheet workSheet = (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;
            while ( ((Excel.Range)workSheet.Cells[rowIndex,colIndex1]).Value2 != null )
               rowIndex = 2+index;
               string firstName = ((Excel.Range)workSheet.Cells[rowIndex,colIndex1]).Value2.ToString();
               string lastName = ((Excel.Range)workSheet.Cells[rowIndex,colIndex2]).Value2.ToString();
               Console.WriteLine("Name : {0},{1} ",firstName,lastName);
         catch(Exception ex)

I hope this is what you are looking for.
All the very best.
Alpesh Patel.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
There is one easy of reading excel file from .Net application.

string strFilePath = "C:\A.xls";
string excelConnectionString = "Dsn=Excel Files;dbq=" + strFilePath + ";defaultdir=" + ";driverid=790;maxbuffersize=2048;pagetimeout=5";
                    //Load Open detals
                    using (OdbcConnection connection = new OdbcConnection(excelConnectionString))

                            OdbcCommand command = new OdbcCommand("Select [ID], [Status],[Created] FROM [Open$]", connection);
                            OdbcDataAdapter da = new OdbcDataAdapter(command);
                            da.Fill(dsSummary, "Open");

Calling Com services is very slow process becaue it is remote procedure call .
 opening OBdc connection or OLedb  is an effeicent way you can easily filter data as want but in
excel object it iterate row by row and cause increase in condition or check you apply for filter.
In calling Excel object cause some problem while closing its object , if program breaks without closing excel
object it remain open until you by force kill them from task manager.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.