Click here to Skip to main content
Click here to Skip to main content

Loading and reading Microsoft Excel file content using C#

By , 19 Oct 2005
 

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:

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)

About the Author

_duk_
Russian Federation Russian Federation
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalthxmemberhamdynassar15 May '11 - 23:54 
thx a lot it help me too much
Generalreading the Microsoft Excel file contents using C#membervishwa1327 Aug '09 - 6:00 
Hi,
 
I am trying to read excel 2003 xls file in visual studio 2008 by using the code published in this website "Loading and reading the Microsoft Excel file contents using C#" By _duk_
 
The file test.xls is exist in the path.
 
But am getting the below error.
 
System.Runtime.InteropServices.COMException was unhandled
HelpLink="C:\\Program Files\\Microsoft Office\\OFFICE11\\1033\\xlmain11.chm"
Message="'c:\\test.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files on the File menu, make sure that the file has not been renamed, moved, or deleted."
Source="Microsoft Office Excel"
ErrorCode=-2146827284
StackTrace:
at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in C:\VSTAF\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 32
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsApplication1.Program.Main() in C:\VSTAF\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
 
can anyone tell me the solution
 
Thanks in advance
GeneralRe: reading the Microsoft Excel file contents using C#membertripathy.rajendra@gmail.com24 Sep '09 - 16:02 
Hi vishwa.
Its bit late for your solution but it may help you.
 
you need to add a dll (Microsoft.Office.Interop.Excel.dll)as reference
 
then use this as namespace-
 
using Excel = Microsoft.Office.Interop.Excel;
 
Hope this'll relief your headache.
 
Cheers.
Raj.
GeneralReference to the Excel Object librarymemberAACINC28 Jan '09 - 4:51 
In Visual Studio 2008 what are the References to include?
Should they be COM interop?
GeneralException in while loopmemberjacky333319 Jan '09 - 14:51 
One suggestion: Move the row: rowIndex = 2+index;
to the end of the while loop, or else there will be exception thrown.
 
Hope I can help U

QuestionHow to read excel file using VC++memberTammanna_19847 May '08 - 23:33 
Hi,
I want to read excel file using VC++. If anybody knows plz share.
Generalthis code does not read the date format in excel filemembermurugapandiyan10 Nov '07 - 18:50 
if i read the excel file its contains a date format
the c# is considered as a text or decimal value so how to
Read the date formated column in excel file
 
muruga
GeneralRe: this code does not read the date format in excel filememberCikaPero18 Apr '10 - 23:10 
Hi,
 
you could try this Excel C# library. It handles DateTime type correctly.
 
Also if you are importing Excel to DataSet and column types in Excel and DataSet are different, you can easily make appropriate conversion, like in this code snippet:
 
var ef = new ExcelFile();
ef.LoadXls("Excel file.xls");
 
// DataSet schema has to be defined before this.
for(int i = 0; i < ef.Worksheets.Count; ++i)
{
	var ws = ef.Worksheets[i];
	// Manage ExtractDataError.WrongType error
	ws.ExtractDataEvent += (sender, e) =>
	{
		if (e.ErrorID == ExtractDataError.WrongType)
		{
			if (e.Mapping.DataSetColumn == "time1" || e.Mapping.DataSetColumn == "time2")
			{
				e.DataTableValue = DateTime.Parse(e.ExcelValue);
				e.Action = ExtractDataEventAction.Continue;
			}
		}
	};
	// Extract data to DataTable
	ws.ExtractToDataTable(dataSet.Tables[i], ws.Rows.Count, ExtractDataOptions.StopAtFirstEmptyRow, ws.Rows[0], ws.Columns[0]);
}

GeneralReading Excel (Office 1997)memberStar Dreamer25 Sep '07 - 6:34 
Hi ,
I have written a code to read Excel 2003 . But my user has Office 97 .
It throws an exception at
 
// code for creating an object of Excel.ApplicationClass()
//create a workBook object ...
 
excelObj.Workbooks.Open ( StrFilename,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,false,Missing.Value,Missing.Value,Missing.Value);
 
Can you provide any solution for this ?

 
Regards,
Tara

GeneralRe: Reading Excel (Office 1997)memberStar Dreamer25 Sep '07 - 6:36 
I forgot to mention that the Exception is Null Reference Error .
 
Regards,
Tara

QuestionReading From Excel in C# and showing it and Sharepoint server 2007memberkhan_SharePoint26 Jul '07 - 23:18 
Dear fellows
 

 
I have problem about which i donot from where i can get help.
 

 
What is Working:
 

 
I have made a ASP.NET (C#) application that is reading Data from Excel (cell b cell). That is working fine and i can check it in browser.
 

 
Problem:
 

 
Now using this code i made a web part in C# and i want to show it in SharPoint Server 2007 site page. Now that is not working , thats mean not showing the web part on the page.
 

 
And when i comment the excel ralated code in web part coding and check it at SharePoint server, web part works.
 

 
I donot know what to do, Please Help
 

 
Piece of code is:
 

 
Excel.Application app = new Excel.Application();
 
Excel.Workbook wbook = null;
 
Excel.Worksheet wsheet = null;
 
Excel.Range range = null;
 
app.Visible = false;
 
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
 
string filepath = inputFile1.Value.ToString();
 
if (filepath != "")
 
{
 
wbook = app.Workbooks.Open(filepath, Missing.Value, Missing.Value, Missing.Value,
 
Missing.Value, Missing.Value, Missing.Value,
 
Missing.Value, Missing.Value, Missing.Value,
 
Missing.Value, Missing.Value, Missing.Value,
 
Missing.Value, Missing.Value);
 

 
string currentSheet = "Sheet1";
 
wsheet = (Excel.Worksheet)wbook.Worksheets.get_Item(currentSheet);
 
range = wsheet.get_Range("B6", "H20");
 
System.Array myvalues = (System.Array)range.Cells.Value2;
 
valueArray = ConvertToStringArray(myvalues);
 

 
if (app != null)
 
{
 
app.Workbooks.Close();
 
app.Quit();
 
}
 
app = null;
 
wsheet = null;
 
range = null;

 
Asif khan
QuestionDoes this work online?memberMember #38635796 Mar '07 - 9:56 
Hi there,
 
I've created a web using visual studio and c#. I can use your code no problem when i'm running it off my local host. However once it's hosted i'm getting the following error:
 
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 
Exception Details: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154.
 
Source Error:
 

Line 54: {
Line 55: //sets up an excel class called excelApp
Line 56: Excel.Application excelApp = new Excel.ApplicationClass();
Line 57: Excel.Workbook newWorkbook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Line 58:
 
Is it at all possible to use this code online??
 
Thanks,
 
Adrian.
AnswerRe: Does this work online?memberkevgriffin27 Mar '07 - 1:55 
Essentially what it is says (I think) is that the Excel Com libs are not available online...
or at least, not available in the environment you are hosted in.
GeneralRe: Does this work online?membershaistaShaikh30 Jun '08 - 23:29 
I want to import data from excel 2007 file. I am getting "COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005." error while creating object of Application class. But note that the Microsoft office is not installed on my machine. I want to import excel file without installing the micrsoft excel?
GeneralRe: Does this work online?membercodevigilante26 Feb '09 - 11:00 
Are you serious? This is like saying I want to build a house but I don't want to use any materials.
GeneralNot all Excel instances are being destroyedmembereyasso23 Dec '06 - 19:37 
I tried this sample and when i opened my "Task Manager" I saw that there are many instances of Excel. Any reason why?
 

GeneralRe: Not all Excel instances are being destroyedmemberkevgriffin26 Mar '07 - 22:30 
Yes, the author failed to extensively test his application
 
Use the following to ensure a complete closure of the process.
 
Please not this is not the complete solution. If the program exits with an exception
before this point, instances may not be closed as your workbook will be unavailable.
 
usage: shutDownExcel(workSheet,workBook,app);
 
#region Close Excel
// from microsofts MSDN
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
o = null;
}
}
//not from the msdn
private void shutDownExcel(Excel.Worksheet workSheet, Excel.Workbook workBook, Excel.ApplicationClass app) {
NAR(workSheet);
workBook.Close(false, false, Type.Missing);
NAR(workBook);
app.Quit();
NAR(app);
}
 
#endregion
GeneralVery Poor PerformancememberANIL KUMAR SHARMA (INDIA)3 Jun '06 - 18:08 
Hi,
The performance using the code is very poor, you can try is using just 5000 rows with say 10 columns and try to copy/write that, will take more than 5 min. OMG | :OMG: even on 3GHz Machine WTF | :WTF: .
 
thanks Rose | [Rose]
anil
(pl)
india
GeneralRe: Very Poor Performancememberlaughingandliving20 Jul '06 - 17:00 
Um, DUH! You can't possibly expect excel to perform like SQLServer with that kind of data. Sheesh.
 
void (*)()
GeneralRe: Very Poor PerformancememberJFMiller21 Aug '06 - 11:25 
Yes, unfortunately I've noticed this too. Not much you can do, it's the way the old COM objects are set up. You have to get each column individually. If only there was a way to get a bunch of columns at once.
 
One way I've found to get data from an xls a bit faster is to write an excel macro to write the data into a CSV file, then read the CSV file. You can use the Excel libraries mentioned in this post to execute the macro (see http://support.microsoft.com/?kbid=306683)
 
John
GeneralRe: Very Poor PerformancememberBarbaMariolino16 Jun '08 - 0:15 
Hi,
 
Excel Automation has many issues (not just with performance). As you probably know the best way to work with Excel file is by using some third party component. I recommend you to try GemBox.Spreadsheet - .NET component for reading/writing Excel files (XLS, XLSX and CSV) and writing to HTML[^]. Here are a few reasons that Explain why is GemBox.Spreadsheet better than Excel Automation[^].
 
There is also a free version of GemBox.Spreadsheet[^] available. Free version comes with 150 rows limit and can be used in commercial applications.
 
Mario
GemBox Software[^]
--
GemBox.Spreadsheet for .NET - Easily read and write Excel (XLS, XLSX or CSV)
or export to HTML files from your .NET apps
[^].
--
GeneralRe: Very Poor Performancememberronny_2955 Jan '09 - 19:09 
Try this : http://free.netartmedia.net/CSharp/CSharp22.html
Generalthe code dosnt read the dateformatmembersalah_gis3 May '06 - 20:52 
the code dosnt read the dateformat
 
salah
gis member
GeneralRe: the code dosnt read the dateformatmembermurugapandiyan11 Nov '07 - 1:02 
field1 = ((Excel.Range)workSheet.Cells[rowIndex, ColumnIndex1]).Text.ToString();
Use this code
 

 
Murugupandiyan.k
 
Murugupandiyan.k
QuestionDoesn't exit properlymemberNutter4Ever3 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 properlymemberjouceyc6 Sep '06 - 21:55 
Change the loop to this :
 
{
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);
rowIndex = 2+index; //remove the first line and insert it here
index++;
}
 
This is how I make the loop exit properly.

GeneralRe: Doesn't exit properlymemberNutter4Ever7 Sep '06 - 9:54 
Ah thanks for that.
 
Now I'll just have to try and remember what it was I needed it for Smile | :) Still thanks all the same, it still might come in handy for something I'm working on.
 
Unemployed Ex-Student Bum - Will work for coffee.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 19 Oct 2005
Article Copyright 2005 by _duk_
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid