The Wayback Machine - https://web.archive.org/web/20090211134139/http://www.codeproject.com:80/KB/office/csharp_excel.aspx
Click here to Skip to main content
5,879,438 members and growing! (18,001 online)
Enterprise Systems » Office Development » Microsoft Excel     Beginner License: The Code Project Open License (CPOL)

Opening and Navigating Excel with C#

By Narsters

Introduction to manipulating Excel with C#.
C#Windows, .NET, .NET 1.0, Win2K, WinXP, Win2003VS.NET2002, Visual Studio, Dev

Posted: 2 Oct 2003
Updated: 2 Oct 2003
Views: 407,187
Bookmarked: 139 times
Announcements
Loading...



Advanced Search
Sitemap
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
102 votes for this Article.
Popularity: 8.61 Rating: 4.29 out of 5
7 votes, 6.9%
1
1 vote, 1.0%
2
10 votes, 9.8%
3
31 votes, 30.4%
4
53 votes, 52.0%
5

Introduction

This is a short introduction to opening an existing Microsoft Excel spreadsheet using Visual C# .NET. The computer must have Excel installed on the system for this code to run properly. The Excel assembly is used to open and manipulate Excel spreadsheets.

Code Explanation

First, the Excel assembly must be added to the project. To do this you must add a reference to the Excel 10 Object Library (Excel XP) by going to the Project -> Add Reference  menu item. Go to the COM tab of the dialog box that pops up and scroll down the Excel 10 Object Library. Double click on it and press OK. This adds the reference to your project. In the "using" section of your code, type

    using Excel; 

Once the assembly is added to the project, a new application needs to be created:

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

If you want to make Excel visible to the user you have to set the Visible property to true, the default is false.

    excelApp.Visable = true;

The code above opens the Excel application, in order to use the application, you have to open a workbook by creating a Workbook object. You can open a new blank workbook by using the following code:

    Excel.Workbook newWorkbook = 
        excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

The preceding code opens a blank workbook with one sheet. The .Add method takes a template object, the XlWBATemplate.xlWBATWorksheet object is a built in template for a blank workbook.

If you want to open an existing document for editing instead of creating a new one, you can use the following code to create a Workbook object:

    string workbookPath = "c:/SomeWorkBook.xls";
    Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
        0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
        true, false, 0, true, false, false);

The preceding code may need a little explanation. The workbookPath is of course the path to the existing spreadsheet that you want to open. The excelApp.Workbooks.open is a little less obvious. The following is the list of parameters that are passed to the function:

  • WorkBooks.open(string Filename, object UpdateLinks, object ReadOnly, object Format, object Password, object WriteResPassword, object ReadOnlyRecommend, object Origin, object Delimiter, object Editable, object Notify, object Converter, object AddToMru, object Local, object CorruptLoad )

To view the documentation on this function, follow the link Microsoft’s website for further explanation of the function at:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbaxl10/html/xlmthOpen.asp

Once the workbook is either created or opened, you must create a Sheets object that holds the Worksheets within the workbook. The following code will get all of the sheets in the workbook you previously opened.

    Excel.Sheets excelSheets = excelWorkbook.Worksheets;

Now that you have the collection of Worksheets, you must get an individual sheet edit data within.

    string currentSheet = "Sheet1";
    Excel.Worksheet excelWorksheet = 
        (Excel.Worksheet)excelSheets.get_Item(currentSheet);

In the preceding code, you have to type cast the excelSheets.get_Item(string) function because it returns an object. Now that you have the sheet you are ready to access individual cells with the following code:

    Excel.Range excelCell = 
        (Excel.Range)excelWorksheet.get_Range("A1", "A1");

The get_Range function must take two parameters. If the two parameters are equal, a single cell is selected; otherwise a range of cells will be selected. Again you have to type cast the return value of the function. Once you have a cell object, your can set its value using the .Value2 property, or use any of the other properties to manipulate ranges of cells.

 Msgs 1 to 25 of 259 (Total in Forum: 259) (Refresh)FirstPrevNext
GeneralThe server threw an exception.(Exception from HRESULT: 0x80010105(RPC_E_SERVERFAULT))memberMember 13942177:14 6 Nov '08  
Windows XP Service Pack 3
Microsoft Office 2003 SP3

error:
Microsoft.Office.Interop.Excel.WorkbookClass wkb = (Microsoft.Office.Interop.Excel.WorkbookClass)app.Workbooks.Open(File, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, false, Missing.Value);

How to run application in Windows XP Service Pack 2 is work!
GeneralThanks a bunch!!!!memberArcherthegreat18:12 28 Oct '08  
I've looking everywhere for this.

Thank you so much!

=)

Battlecry: Archer the GREAT !!!

GeneralPopulating an Excel "template" in ASP.NETmemberslapmatt0:03 11 Sep '08  
I have an Excel workbook made up of several sheets. The first sheet contains cells that populate common fields throughout the other sheets.

What I am trying to do is populate pre-defined fields on the first sheet with information from a database and triggering this from a Web page.

Obviously the Web server does not have Excel installed, but you can assume the client machine does.

How do I go about trying to achieve this?

Thanks in advance!
GeneralRe: Populating an Excel "template" in ASP.NETmemberJeff Ruys10:59 12 Sep '08  
I am pretty sure that the server would have to have Excel installed on it since all of the code behind your page would be running on the server.
QuestionCom Exception 0x80028018 TYPE_E_INVDATAREADmembertho_wa2:25 9 Sep '08  
Hi,

I have tried the code (and also other examples found on the internet) but all are resulting in a COM Exception 0x80028018 (TYPE_E_INVDATAREAD) when trying to open the excel sheet.

Here is the complete error message:
------------------------------
System.Runtime.InteropServices.COMException was unhandled
Message="Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))"
Source="Interop.Excel"
ErrorCode=-2147319784
StackTrace:
at Excel.Workbooks.Add(Object Template)
at ExcelExample.ExcelClass.Main(String[] args)
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()
-----------------------------------

I'm using Excel 2003 SP3 (11.8169.8172) with Visual Studio 2005 (8.0.50727.762 - SP.050727-7600) and .NET Framework V2.0.50727 SP1

Any suggestions?

Thanks a lot
Thorsten
AnswerRe: Com Exception 0x80028018 TYPE_E_INVDATAREADmemberJeff Ruys11:21 12 Sep '08  
Unfortunately I am unable to re-create the problem, but here is a suggestion that will hopefully help:

In the project I supplied it has some outdated references, so try adding the new reference from the Project->Add References... menu choice. Go to the COM tab and choose the most current Microsoft Excel library. Then go to the References folder under the solutions explorer and remove the Excel and Microsoft.Office.Core references. If you get some compile errors like Excel is not a valid reference or something like that, put this into the using directives:
using Excel = Microsoft.Office.Interop.Excel;

I am wondering if the the Excel and Microsoft.Office.Core references are causing some conflicts.

I hope this helps.
AnswerRe: Com Exception 0x80028018 TYPE_E_INVDATAREADmemberofercinn3:21 17 Sep '08  
Solution from http://www.gotdotnet.ru/Forums/Common/290167.aspx[^]
Before creating Excel object

System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

After closing Excel:

System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
QuestionHow to move to last row of Active WorkSheet programmatically using C#?memberDinesh Patel20:56 18 Aug '08  
I want same feature like Ctrl + End, which takes me to the last avaialable blank row in an Active WorkSheet. Please help me
AnswerRe: How to move to last row of Active WorkSheet programmatically using C#?memberJeff Ruys9:26 21 Aug '08  
You need to use the .SpecialCells method.

I have not tested this just yet, but here it goes. To get to the last cell in the last column you can use this:

Where curCell is a an Excel.Range object.

curCell.SpecialCells(xlCellTypeLastCell, System.Type.Missing).Select

Here is the method signature:
.SpecialCells(Type, Value)
The values for Type and Value are listed below.

Type Required XlCellType. The cells to include.
XlCellType can be one of these XlCellType constants.
xlCellTypeAllFormatConditions. Cells of any format
xlCellTypeAllValidation. Cells having validation criteria
xlCellTypeBlanks. Empty cells
xlCellTypeComments. Cells containing notes
xlCellTypeConstants. Cells containing constants
xlCellTypeFormulas. Cells containing formulas
xlCellTypeLastCell. The last cell in the used range
xlCellTypeSameFormatConditions. Cells having the same format
xlCellTypeSameValidation. Cells having the same validation criteria
xlCellTypeVisible. All visible cells

Value Optional Variant. If Type is either xlCellTypeConstants or xlCellTypeFormulas, this argument is used to determine which types of cells to include in the result. These values can be added together to return more than one type. The default is to select all constants or formulas, no matter what the type. Can be one of the following XlSpecialCellsValue constants:
XlSpecialCellsValue can be one of these XlSpecialCellsValue constants.
xlErrors
xlLogical
xlNumbers
xlTextValues
QuestionHow to insert a row from one excel to another using c#.net 2005?memberVDivyaReddy0:15 14 Aug '08  
Hi

Need help!

I have 2 excels,I am comparing the 1st with 2nd.
If a row in 1st excel is not found in 2nd excel, then I need to insert the row from 1st excel to 2nd excel.how do i do it?
AnswerRe: How to insert a row from one excel to another using c#.net 2005?memberrajkumarsingh1:18 3 Oct '08  
U can use StreamReader and StreamWritter.........
QuestionHelp! C# Excel 'get_range' returning value for cell in the next rowmemberMember 271871110:44 10 Jul '08  
Hi,

I have a huge and very complex spreadsheet some of the rows locked, hidden, merged, grouped, with formulae all over, protected (and what not!); that I'm supposed to read within C#.

I had some initial problems doing this with the password protection, COM errors etc.. that I could resolve.

Now I'm having an unusual problem..

I read a range of values using 'a while loop' and 'get_range' as follows:
         
      object m;
      m = System.Reflection.Missing.Value;
                    
      //first time
      string strPMSheetField = "BN";
      string strPMCurRow = "6";

      objPMRange = (Excel.Range)excelPMWorksheet.get_Range(strPMSheetField + strPMCurRow, m);
      if (objPMRange.Value2 != null)
            strName = objPMRange.Value2.ToString();
      else
            strName = "";

      //loop down the rows
      while (strName != "")
      {              
     //add the name to my array list etc.   //
              
     //set next row no.
     strPMCurRow = Convert.ToInt32(strPMCurRow) + 1;

            //read data
            objPMRange = (Excel.Range)excelPMWorksheet.get_Range(strPMSheetField + strPMCurRow, m);
            if (objPMRange.Value2 != null)
                     strName = objPMRange.Value2.ToString();
            else
                     strName = "";
    

      }

What is happening is until some rows it gets the value fine, but at some specific rows, it skips reading the current row and
gets the values in the following cell (row).

Not sure, but I'm guessing that some rows are 'locked'/'hidden' under a specific logic and the get_range when it comes across such 'locked' field is simply going to the next one. ???

I couldn't find that specific logic anywhere in spreadsheet to hide/lock but I'm assuming it.

In the debug it always shows 'hidden=false', 'locked=false' or says that property 'threw exception' Smile

My Trials:

1. I tried to set these before I read the value but in vain:
                        excelPMWorksheet.get_Range(strPMSheetField + strPMCurRow, m1).Locked = false;
                        excelPMWorksheet.get_Range(strPMSheetField + strPMCurRow, m1).EntireRow.Locked = false;
                        excelPMWorksheet.get_Range(strPMSheetField + strPMCurRow, m1).EntireRow.Hidden = false;
                   
2. I tried to read the whole range BN6:BO136 into a 2-dim Array, the result is the same: If there are 50 rows only 46 would show up and 4 are skipped.

3. I wrote a VBA Module to see if it happens there - it worked fine there (no rows were skipped).


Please help.. I'm lost..

-ap
AnswerRe: Help! C# Excel 'get_range' returning value for cell in the next rowmemberJeff Ruys18:08 10 Jul '08  
I am not sure what is going on, there must be some strange permissions on the cells. I tried it with just a sample sheet with some rows hidden and some rows locked and it got every value. I have tried just about everything I can think cell formatting wise to get it to skip some rows with no luck. The only suggestion that I have is to take a hard look at the rows that are giving you problems and check out their formatting. Sorry to not be any more help.
Generalto close the workbookmemberMember 151816711:00 8 May '08  
after I finished working with a workbook, should I "kill" the worksheet object or leave it to the garbage collector ?

in order to close the workbook what overloads I have to load?

excelWorkbook.Close(___,____,____); ?


I'm almost finished working on my homework thanks to you Smile

(i have to copy the results to dataset and to show a chart, but i know how to do it)


Thanks to you and to THE CODE PROJECT !!!!
GeneralI DID IT !!!!!!!!!!!!!!!!!!!!!!!!memberMember 151816710:52 10 May '08  
excelWorkbook.Close(bool,bool,bool);

I coulnd understand it at first because in the msdn instead of "bool" (true/false) was written "object so I couldnt understand what they ment to say.....

sometimes it's very frastrating to code but I guess this was the easiest "problem" to handle.
GeneralHi. How to copy a range of column/cells from one excel document to another ?memberMember 151816712:48 7 May '08  
hi I'm new in programming...

and where can I see all the procedures in the Excel class ?

thanks a lot !!!
GeneralRe: Hi. How to copy a range of column/cells from one excel document to another ?memberJeff Ruys17:21 7 May '08  
Here is a link the all of the objects in the Excel Namespace: http://msdn.microsoft.com/en-us/library/bb149081.aspx[^]

They are pretty much the same functions that you can find in VBA within Excel, so you can look at the object model in VBA for just about the same thing.
GeneralRe: Hi. How to copy a range of column/cells from one excel document to another ?memberMember 15181675:39 8 May '08  
OK. I saw that there are excel 2003 documentation (VBA) and 2007(the link in your answer).

I found what I wanted but there are only vb examples... When I tried to convert it to c# I got errors...
all I need to do is to copy a range of columns from one workbook to anoter through c#.

can you advice me about this?



http://msdn.microsoft.com/en-us/library/bb178833.aspx
http://msdn.microsoft.com/en-us/library/bb178854.aspx
http://msdn.microsoft.com/en-us/library/bb210384.aspx
Worksheet.Copy Method
http://msdn.microsoft.com/en-us/library/bb179176.aspx
Worksheet.Paste Method
http://msdn.microsoft.com/en-us/library/bb179200.aspx


With Worksheets("Sheet1")
.Range("C1:C5")
.Copy.Range("D1:D5")
.PasteSpecial _
Operation:=xlPasteSpecialOperationAdd
End With


When I tried to convert from vb to c# i got this :


CONVERSION ERROR: Code could not be converted. Details:

-- line 3 col 75: invalid EndOfStmt

Please check for any errors in the original code and try again.




thank you very much.
GeneralRe: Hi. How to copy a range of column/cells from one excel document to another ?memberJeff Ruys7:13 8 May '08  
Here is an Example of how you could do it:
Excel.Range destination = (Excel.Range)excelWorksheet.get_Range("C1", "C4");
excelWorksheet.get_Range("A1", "A4").Copy((Excel.Range)destination);


This takes the Contents of A1:A4 and copies them over to C1:C4. Hope this helps.
GeneralRe: Hi. How to copy a range of column/cells from one excel document to another ?memberMember 15181679:23 8 May '08  
Thanks a LOT !!!!!!!

this is how I did it (with your assistance, of course)


Excel.Application excelApp = new Excel.ApplicationClass();
excelApp.Visible = true;
string workbookPath = "e:/111.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);
string workbookPath2 = "e:/222.xls";
Excel.Workbook excelWorkbook2 = excelApp.Workbooks.Open(workbookPath2, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets excelSheets2 = excelWorkbook2.Worksheets;
string currentSheet2 = "Sheet1";
Excel.Worksheet excelWorksheet2 = (Excel.Worksheet)excelSheets2.get_Item(currentSheet2);
Excel.Range destination = (Excel.Range)excelWorksheet2.get_Range("C1", "D9");
excelWorksheet.get_Range("A1", "B9").Copy((Excel.Range)destination);


by the way, is copying thousands of columns is fast with this Excel Engine ?
or in that case I sould use third party components(like Infragistics Excel Engine) ?

thanks again, by the way how did you learn to work with this Excel class ?
QuestionCom exceptionmembermanu4ever11:22 22 Apr '08  
Hi,
I am using the above code in Visual studio 2005, but I keeping getting Com Exception error
Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))

any suggestions whats going wrong?
Thanks
/M
GeneralRe: Com exceptionmemberJeff Ruys11:54 22 Apr '08  
That is odd, when are you getting the exception, at Compile Time? I have used the code in VS 2005 and have not had any problems. I assume you have Excel installed on the machine you are getting the exception from.
GeneralRe: Com exceptionmembermanu4ever12:05 22 Apr '08  
I am getting error at runtime on this line
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
GeneralRe: Com exceptionmembermanu4ever12:16 22 Apr '08  
Here is the exception detail:

System.Runtime.InteropServices.COMException was unhandled
Message="Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))"
Source="Interop.Excel"
ErrorCode=-2147352565
StackTrace:
at Excel.Sheets.get_Item(Object Index)
at ExcelExample.ExcelClass.Main(String[] args) in C:\Documents and Settings\Manu\My Documents\Visual Studio 2005\Projects\ExcelExample\ExcelClass.cs:line 38
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()
GeneralRe: Com exceptionmemberJeff Ruys14:22 22 Apr '08  
I just played with it a little in VS 2005 and did not have a problem. Are you sure that the Sheet you are trying to access exists with the name you are using? Also what version of Excel are you using, I have tested this on XP and 2003 formats.

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 Oct 2003
Editor: Nishant Sivakumar
Copyright 2003 by Narsters
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project