Click here to Skip to main content
15,905,877 members
Articles / Programming Languages / C#

Loading and reading Microsoft Excel file content using C#

Rate me:
Please Sign up or sign in to vote.
1.71/5 (41 votes)
19 Oct 2005CPOL 362.6K   50   29
Using the Excel namespace in C#, we can load or open an Excel file and read the cell contents.

Introduction

This is a test application which tells how to use the Microsoft Excel 10.0 Object Library to load/read Excel content.

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

The application is a Console Application developed using VC#.

Steps

  1. Include the following references to the project:
    • Microsoft Excel 10.0 Object Library
    • Microsoft Office 10.0 Object Library
  2. Include the required namespace: using Excel;.
  3. Create the objects ExcelApplicationClass, WorkBook, and Range.

Here is the complete code:

C#
using System;
using Excel; 

namespace TestExcel
{
 /// <summary>
 /// Summary description for ExcelApplication.
 /// </summary>
 class ExcelApplication
 {
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      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, 
                                                      0, 
                                                      true, 
                                                      5,
                                                      "",
                                                      "",
                                                      true,
                                                      Excel.XlPlatform.xlWindows,
                                                      "\t",
                                                      false,
                                                      false,
                                                      0,
                                                      true,
                                                      1,
                                                      0);
         // 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; 
         try
         {
            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);
               index++;
            }
         }
         catch(Exception ex)
         {
            app.Quit();
            Console.WriteLine(ex.Message);
         }
      }
   }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralVery Poor Performance Pin
ANIL KUMAR SHARMA (INDIA)3-Jun-06 18:08
ANIL KUMAR SHARMA (INDIA)3-Jun-06 18:08 
GeneralRe: Very Poor Performance Pin
JakeSays20-Jul-06 17:00
JakeSays20-Jul-06 17:00 
GeneralRe: Very Poor Performance Pin
JFMiller21-Aug-06 11:25
JFMiller21-Aug-06 11:25 
GeneralRe: Very Poor Performance Pin
FilipKrnjic16-Jun-08 0:15
FilipKrnjic16-Jun-08 0:15 
GeneralRe: Very Poor Performance Pin
ronny_2955-Jan-09 19:09
ronny_2955-Jan-09 19:09 
Generalthe code dosnt read the dateformat Pin
salah_gis3-May-06 20:52
salah_gis3-May-06 20:52 
GeneralRe: the code dosnt read the dateformat Pin
Murugu Pandiyan11-Nov-07 1:02
Murugu Pandiyan11-Nov-07 1:02 
QuestionDoesn't exit properly Pin
Nutter4Ever3-Feb-06 6:07
Nutter4Ever3-Feb-06 6:07 
Firstly I'm having to use Excel 9.0 rather than Excel 10.0 Not sure if thats whats causing this problem. Anyone know where/how to update this without having to go get a new copy of Office/Excel.

Anyway if thats not the problem the code doesn't exit properly it always throw the an exception when it runs.

I've got two rows in the test.xls and it reads them properly, but when it's done with that it throws and expection and then dies.

After the While loop, which is supposed to terminate when it runs out of stuff, I added 'Console.WriteLine("Foo");' It never makes it up to this point. It just wrote out the two rows of the excel file and then throws the exception (So its not a case, which I suspected, that it runs out of things to do and thus jumps from the Try method to Catch method.

I tried modifying the loop to a do-while, but that didn't give any better results.

I suspect that its a case that its not reading the empty cells as null but something else, and something that it can't type-cast and thus it throws an exception.

Anyway for the purposes of completeness follows is a copy of the command window output after running the program. Thanks for any feedback or bug-fixes anyone posts here.

Nutter

D:\My Documents\Programming Projects\ConsoleApplication1\bin\Debug>consoleapplic
ation1
Name : Number or text,23
Name : Peter Pan,Pan
Object reference not set to an instance of an object.

Unemployed Ex-Student Bum - Will work for coffee.
AnswerRe: Doesn't exit properly Pin
jouceyc6-Sep-06 21:55
jouceyc6-Sep-06 21:55 
GeneralRe: Doesn't exit properly Pin
Nutter4Ever7-Sep-06 9:54
Nutter4Ever7-Sep-06 9:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.