Click here to Skip to main content
11,567,922 members (45,409 online)
Click here to Skip to main content

Opening and Navigating Excel with C#

, 17 Apr 2012 CPOL 1.2M 21.7K 242
Rate this:
Please Sign up or sign in to vote.
Introduction to manipulating Excel with C#.

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)

Share

About the Author

Narsters
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralRe: Com exception Pin
Jeff Ruys22-Apr-08 18:46
memberJeff Ruys22-Apr-08 18:46 
Generalread an Excel range (cell) of date type into C# string Pin
Member 271871120-Mar-08 11:00
memberMember 271871120-Mar-08 11:00 
AnswerRe: read an Excel range (cell) of date type into C# string Pin
Jeff Ruys20-Mar-08 14:40
memberJeff Ruys20-Mar-08 14:40 
GeneralRe: read an Excel range (cell) of date type into C# string Pin
Member 271871121-Mar-08 4:15
memberMember 271871121-Mar-08 4:15 
AnswerRe: read an Excel range (cell) of date type into C# string Pin
fRenato17-Jun-08 2:50
memberfRenato17-Jun-08 2:50 
Questionhow to append data into already existing Excel sheet Pin
shraddha19046-Mar-08 21:57
membershraddha19046-Mar-08 21:57 
AnswerRe: how to append data into already existing Excel sheet Pin
Jeff Ruys7-Mar-08 4:37
memberJeff Ruys7-Mar-08 4:37 
Questionhow to append data into already existing Excel sheet???? Pin
Krishnaraj Barvathaya B6-Mar-08 21:54
memberKrishnaraj Barvathaya B6-Mar-08 21:54 
i am automating my formatted excel work book. now i want to first retreive the last filled row of an already existing excel sheet and then want to fill my array day next to that row. please help me ASAP. its bugging me.....Confused | :confused:

shraddha

shradhs..
QuestionExport to excel ,Help me Out Pin
purushothamanv3-Mar-08 18:25
memberpurushothamanv3-Mar-08 18:25 
QuestionDoes it work for web apps Pin
Member 322823914-Dec-07 5:05
memberMember 322823914-Dec-07 5:05 
GeneralRe: Does it work for web apps Pin
BarbaMariolino28-Apr-08 1:36
memberBarbaMariolino28-Apr-08 1:36 
QuestionCollect multiple .xls files into one workbook Pin
cybertecgroup17-Oct-07 10:07
membercybertecgroup17-Oct-07 10:07 
QuestionType or namespace name 'Excel' not found Pin
crystallized29-Jun-07 5:32
membercrystallized29-Jun-07 5:32 
AnswerRe: Type or namespace name 'Excel' not found Pin
Jeff Ruys29-Jun-07 9:12
memberJeff Ruys29-Jun-07 9:12 
AnswerRe: Type or namespace name 'Excel' not found Pin
crystallized29-Jun-07 9:38
membercrystallized29-Jun-07 9:38 
GeneralRe: Type or namespace name 'Excel' not found Pin
Jeff Ruys29-Jun-07 9:49
memberJeff Ruys29-Jun-07 9:49 
GeneralRe: Type or namespace name 'Excel' not found Pin
crystallized29-Jun-07 10:06
membercrystallized29-Jun-07 10:06 
GeneralRe: Type or namespace name 'Excel' not found Pin
Tschebbe18-Sep-09 3:08
memberTschebbe18-Sep-09 3:08 
GeneralRe: Type or namespace name 'Excel' not found Pin
Narsters18-Sep-09 4:13
memberNarsters18-Sep-09 4:13 
QuestionFind & Replace capability Pin
Mike Donner20-Jun-07 7:29
memberMike Donner20-Jun-07 7:29 
AnswerRe: Find & Replace capability Pin
Jeff Ruys20-Jun-07 8:34
memberJeff Ruys20-Jun-07 8:34 
GeneralRe: Find & Replace capability Pin
Mike Donner21-Jun-07 7:23
memberMike Donner21-Jun-07 7:23 
GeneralRe: Find & Replace capability Pin
Member 45951627-Dec-07 5:30
memberMember 45951627-Dec-07 5:30 
GeneralRe: Find & Replace capability Pin
Member 45951627-Dec-07 5:39
memberMember 45951627-Dec-07 5:39 
Questionhow to compare two excel cell values Pin
sureshkumargundala12-Jun-07 19:39
membersureshkumargundala12-Jun-07 19:39 

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

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

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