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   
QuestionExport to excel ,Help me Out Pinmemberpurushothamanv3 Mar '08 - 18:25 
QuestionDoes it work for web apps PinmemberMember 322823914 Dec '07 - 5:05 
QuestionCollect multiple .xls files into one workbook Pinmembercybertecgroup17 Oct '07 - 10:07 
QuestionType or namespace name 'Excel' not found Pinmembercrystallized29 Jun '07 - 5:32 
QuestionFind & Replace capability PinmemberMike Donner20 Jun '07 - 7:29 
Questionhow to compare two excel cell values Pinmembersureshkumargundala12 Jun '07 - 19:39 
QuestionHow do I get the default worksheet? PinmemberKomputec11 Jun '07 - 10:05 
Generalproblem wih excel reference Pinmemberchannaca26 May '07 - 20:00 
GeneralCopy rows/columns from one excel file to another excel file [modified] Pinmembermujahidcodeproject22 Feb '07 - 0:09 
GeneralSelecting specific cells and writing them to a database [modified] Pinmemberadmol15 Feb '07 - 0:45 
QuestionQueryInterface failed Pinmembersteve_dee9 Jan '07 - 1:04 
Generalprinting excel table Pinmemberrawbone226 Dec '06 - 10:45 
Questionhow to copy a sheet to another new workbook? Pinmemberfivehun19 Nov '06 - 17:48 
QuestionDoesn't open as writable, pops up "Read/Write" dialog Pinmembersbernardi17 Oct '06 - 10:35 
GeneralProblem with office automation PinmemberIamADotNetGuy25 Sep '06 - 18:41 
GeneralError Message Question Pinmembervidi005 Sep '06 - 7:41 
QuestionHow to open an ExcelWorkbook Pinmemberemrek29 Aug '06 - 4:05 
Questionhow to set font style Pinmemberchandra9997779 Aug '06 - 0:40 
QuestionHow can i insert column Pinmemberchandra9997778 Aug '06 - 19:03 
QuestionHow to save the .xls file? [modified] Pinmemberchandra9997774 Aug '06 - 20:09 
QuestionHow to read and write .xls file in the backgoung Pinmemberchandra9997773 Aug '06 - 18:09 
QuestionHow to read string from merge cell Pinmemberchandra9997773 Aug '06 - 4:06 
Questionread and write .xls files Pinmemberchandra9997773 Aug '06 - 2:39 
Questionwrite the readed cell value in another .xls file? Pinmemberchandra9997772 Aug '06 - 20:14 
Questionhow to raed and write .xls file giving cellvalue as input Pinmemberchandra9997772 Aug '06 - 0:34 
QuestionCan Excel launch from DLL? Pinmemberustech00719 Jul '06 - 16:41 
GeneralThanks! PinprotectorMarc Clifton8 Jul '06 - 7:44 
GeneralExcel version errors PinmemberSander van B31 May '06 - 21:11 
GeneralThe powerful .net component for excel Pinmemberprivacy space28 May '06 - 23:32 
GeneralVisual Studio 2000 Pinmemberxjli25 Apr '06 - 7:28 
GeneralProblem publishing site - namespace not found Pinmemberdels_cpp24 Apr '06 - 23:20 
GeneralExcel.exe started but not shut down Pinmemberaamax26 Mar '06 - 13:16 
QuestionError "Access Denied" - PLZZZ HELP! PinmemberYukta13 Mar '06 - 0:12 12 
Generalcells with 0 values PinmemberRB@Emphasys27 Feb '06 - 7:50 
Questionhow to make range of cells readonly??? Pinmemberdeepakbadki30 Jan '06 - 1:45 
GeneralError when opening Excel 2003 Pinmembersunil_s17 Jan '06 - 23:18 
GeneralWeb Service Printing PinmemberRichard Zey17 Jan '06 - 10:13 
QuestionReading Tab separated files in Excel Pinmembersunil_s5 Jan '06 - 23:52 
QuestionComprehensive guide for Excel Object ? PinmemberBig Cheese1 Dec '05 - 2:44 
GeneralSpecialCells PinsussAnonymous11 Oct '05 - 5:11 
QuestionProblem with the count of rows and columns PinsussAnonymous11 Oct '05 - 1:24 
Generalexcel page Pinmemberalexby7 Sep '05 - 8:04 
QuestionHow to read only selected range from excel sheet Pinmemberatodmal20 Jul '05 - 1:40 
Generalcheck Excel97 language setting PinmemberUffel31 Jun '05 - 3:56 
GeneralSecurity policy Pinmemberro_angel_bv29 May '05 - 21:22 
GeneralExcel 10 Object Library not available Pinmemberseeker@seekerspalace.com28 May '05 - 4:19 
QuestionHow to read data from Excel using C# PinsussAnonymous5 May '05 - 13:20 
GeneralProblem with Excel Range Names in C# PinmemberUffel326 Apr '05 - 3:11 
GeneralCreate Excel file form aspx.cs Pinsussamyat13 Feb '05 - 22:09 
Generalusing text values to access cell PinsussAnonymous10 Feb '05 - 5:41 
QuestionC#, set an Excel Column to Text? PinsussAnonymous26 Jan '05 - 6:30 

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.130523.1 | Last Updated 17 Apr 2012
Article Copyright 2003 by Narsters
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid