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

Opening and Navigating Excel with C#

By , 17 Apr 2012
 

Introduction 

Note: This article has been updated to interact with Office 2007. I left the old .NET 1.0 solution for Office XP available for download for reference (in case you are using an old version of Office).

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 Microsoft.Office.Interop.Excel library by going to the Project -> Add Reference  menu item. Go to the .NET tab of the dialog box that pops up and scroll down the Microsoft.Office.Interop.Excel list item. Double click on it and press OK. This adds the reference to your project. In the "using" section of your code, type

using Excel = Microsoft.Office.Interop.Excel; 

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

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

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

excelApp.Visible = 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();

The preceding code opens a blank workbook with one sheet. The .Add method optionally takes a template object.  If the parameter is left blank, the default template will be used (like when you open Excel manually).

If you want to open an existing document for editing instead of creating a new one, you can use the following code to open the 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, and if using .NET 4.0 and the Office 2007 library (Microsoft.Office.Interop.Excel library), it is the only parameter required. The rest of the excelApp.Workbooks.open parameters are 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 to Microsoft’s website for further explanation of the function at: http://msdn.microsoft.com/en-us/library/bb179167%28v=office.12%29.aspx

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) method 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 method. 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.

License

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

About the Author

Narsters
Software Developer (Senior)
United States United States
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   
AnswerRe: How to make it work with Excel 2007memberNarsters10 Feb '10 - 18:08 
I am not sure where you got this error, but it is most likely due to the fact you are using Excel 2007. The best advice I can give you is to look at examples for VBA and remember that none of the parameters in the c# methods are optional.
GeneralReading Excel Embeded objectsmemberShrihari Devji7 Jan '10 - 20:15 
HI
I have an excel file to be read in C#. I used the ODBC to read the data from the excel and it works fine. But one of its sheets has embeded objects e.g Textbox in it. I have to read data from that text box. So how can i read this text box data from C#.
GeneralThank you very muchmemberBidesh Mukherjee25 Nov '09 - 0:44 
Hi,
 
I am a C++ developer and wanted to just open an existing excl file from c#. Its a huge relief.
 
Thanks a million.
QuestionWhat exactly are the downloaded source files supposed to do?memberstapes2 Mar '09 - 5:35 
Hi
 
I have downloaded the source files. They don't appear to do anything.
AnswerRe: What exactly are the downloaded source files supposed to do?memberNarsters2 Mar '09 - 6:40 
The code, when set-up will open a Excel file, go to sheet1 and in Cell A1, will write Hi There. Now, there are a couple of things to do before this code works. First, you need to go to the references section and make sure you are referencing the correct version of Excel, I believe the code as is is referencing Office XP (this is older code). Second, you need to make sure you change the path to an existing Excel file (replace c:/SomeWorkBook.xls with a real file). It should run fine from there.
GeneralThe server threw an exception.(Exception from HRESULT: 0x80010105(RPC_E_SERVERFAULT))memberMember 13942176 Nov '08 - 6:14 
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!!!!memberArcherthegreat28 Oct '08 - 17:12 
I've looking everywhere for this.
 
Thank you so much!
 
=)
 
Battlecry: Archer the GREAT !!!

GeneralPopulating an Excel "template" in ASP.NETmemberslapmatt10 Sep '08 - 23:03 
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 Ruys12 Sep '08 - 9:59 
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.
GeneralRe: Populating an Excel "template" in ASP.NETmemberCikaPero12 Apr '11 - 22:37 
Hi,
 
using Excel Interop is not recommended on server, even by Microsoft.
 
I suggest you try some 3rd party alternative like this Excel C# / VB.NET library.
 
Here is a sample how to use it in your Excel ASP.NET app:
DataTable people = (DataTable)Session["people"];
 
// Create excel file.
ExcelFile ef = new ExcelFile();
ExcelWorksheet ws = ef.Worksheets.Add("DataSheet");
ws.InsertDataTable(people, "A1", true);
 
Response.Clear();
 
// Stream file to browser, in required type.
switch (this.RadioButtonList1.SelectedValue)
{
    case "XLS":
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment; filename="
            + "Report.xls");
        ef.SaveXls(Response.OutputStream);
        break;
 
    case "XLSX":
        Response.ContentType = "application/vnd.openxmlformats";
        Response.AddHeader("Content-Disposition", "attachment; filename="
            + "Report.xlsx");
        // With XLSX it is a bit more complicated as MS Packaging API
        // can't write directly to Response.OutputStream.
        // Therefore we use temporary MemoryStream.
        MemoryStream ms = new MemoryStream();
        ef.SaveXlsx(ms);
        ms.WriteTo(Response.OutputStream);
        break;
}
 
Response.End();

QuestionCom Exception 0x80028018 TYPE_E_INVDATAREADmembertho_wa9 Sep '08 - 1:25 
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 Ruys12 Sep '08 - 10:21 
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_INVDATAREADmemberofercinn17 Sep '08 - 2:21 
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;
GeneralRe: Com Exception 0x80028018 TYPE_E_INVDATAREADmemberMember 119956312 Jul '10 - 13:04 
Works for me. Thanks!
GeneralRe: Com Exception 0x80028018 TYPE_E_INVDATAREADmembernafzali15 Sep '11 - 6:05 
tanks a lottttttttttttttttt
QuestionHow to move to last row of Active WorkSheet programmatically using C#?memberDinesh Patel18 Aug '08 - 19:56 
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 Ruys21 Aug '08 - 8:26 
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?memberVDivyaReddy13 Aug '08 - 23:15 
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?memberrajkumarsingh3 Oct '08 - 0:18 
U can use StreamReader and StreamWritter.........
QuestionHelp! C# Excel 'get_range' returning value for cell in the next rowmemberMember 271871110 Jul '08 - 9:44 
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 Ruys10 Jul '08 - 17: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 15181678 May '08 - 10:00 
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 May '08 - 9:52 
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.
QuestionHi. How to copy a range of column/cells from one excel document to another ?memberMember 15181677 May '08 - 11:48 
hi I'm new in programming...
 
and where can I see all the procedures in the Excel class ?
 
thanks a lot !!!
AnswerRe: Hi. How to copy a range of column/cells from one excel document to another ?memberJeff Ruys7 May '08 - 16:21 
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.

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 17 Apr 2012
Article Copyright 2003 by Narsters
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid