Click here to Skip to main content
15,886,873 members
Articles / Programming Languages / C#

Opening and Navigating Excel with C#

Rate me:
Please Sign up or sign in to vote.
4.57/5 (139 votes)
17 Apr 2012CPOL3 min read 2M   28.5K   246   291
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

C#
using Excel = Microsoft.Office.Interop.Excel; 

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

C#
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.  

C#
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:

C#
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: 

C#
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.

C#
Excel.Sheets excelSheets = excelWorkbook.Worksheets;

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

C#
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:

C#
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)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGood one,really helpful Pin
venubattini21-Jul-16 7:09
venubattini21-Jul-16 7:09 
QuestionVery Well Expained Pin
@nkit Bajpai14-Apr-16 23:41
professional@nkit Bajpai14-Apr-16 23:41 
QuestionIssue with Microsoft.Office.Interop.Excel assembly on windows 2008 R2 server. Pin
Member 123024812-Feb-16 1:07
Member 123024812-Feb-16 1:07 
C#
Our task is , we need to run the excel macro through programatically.

In local environment it was working fine, when we follow the below Steps:-

1) Microsoft.Office.Interop.Excel.Application appExcel = new Microsoft.Office.Interop.Excel.Application();

2) Microsoft.Office.Interop.Excel.Workbook workBook = appExcel.Workbooks.Open("FilePath",
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing);

3) appExcel.Run("Macro name", "$W$5", 1, 0, "$Q$11:$Q$112", Type.Missing, Type.Missing, Type.Missing,
 		Type.Missing, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
		Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
 		Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
 		Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Note:-

On localhost everything is working fine and the macro is getting executed.

But the functionality is not working as expected when hosted in IIS(version 7.5).

For this to work the changes which we have done are:-

a) Control Panel -> Administrative Tools -> Component Services
	Computers -> My Computer -> DCOM Config -> Microsoft Excel Application -> Properties
	
    i) Here in the security tab we have Customized all the permissions by adding user(IUSR) and giving him all 
   	access permissions.
    
	After doing these changes we are able to create instance of Interop.Excel.
	But we could not open the workbook.

    ii) In Identity tab of Microsoft Excel Application peroperties, by default "The launching user" is selected.
	
	After changing the value to "The interactive user" we are able to open the workbook.
	But we could not run the macro.

   iii) C:\Windows\System32\config\systemprofile
	
	In this location we have created Desktop folder. For this folder properties, in the security tab we have created user(IUSR) and given full control.
	Now we are able to run the macro and getting the desired output even when running the application on IIS hosted site.

Issue:-

After making all the changes when we have moved the changes to production server, there we could not find Microsoft Excel Application in DCOM Config.
Microsoft Office is not completely installed in production server. Only Excel software was installed on the server.

We are getting null reference exception at below line of code. 

Microsoft.Office.Interop.Excel.Workbook workBook = appExcel.Workbooks.Open("FilePath",
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                       Type.Missing, Type.Missing);

Our production server is running on  windows 2008 R2.

Could any one please suggest the right way to resolve this issue.

Questioncan the excel sheet be formatted before generating? Pin
sarthakm23-May-15 7:15
sarthakm23-May-15 7:15 
QuestionThis might be interesting here: Pin
dietmar paul schoder29-Jul-14 10:34
professionaldietmar paul schoder29-Jul-14 10:34 
AnswerRe: This might be interesting here: Pin
Member 1116567219-Oct-14 19:40
Member 1116567219-Oct-14 19:40 
GeneralRe: This might be interesting here: Pin
dietmar paul schoder19-Oct-14 20:26
professionaldietmar paul schoder19-Oct-14 20:26 
QuestionGet Error in this code Pin
DilipSutariya5-May-14 0:00
DilipSutariya5-May-14 0:00 
QuestionGreat Pin
TopDawg Dawg25-Mar-14 19:05
TopDawg Dawg25-Mar-14 19:05 
QuestionGracias !! Pin
Member 1067956918-Mar-14 3:51
Member 1067956918-Mar-14 3:51 
QuestionHow I can keep lead zeros when get_value? Pin
Paul_ll14-Dec-13 9:36
Paul_ll14-Dec-13 9:36 
QuestionSpreadSheetLight Pin
Terence Wallace25-Nov-13 11:45
Terence Wallace25-Nov-13 11:45 
GeneralMy vote of 4 Pin
jonthan3417-May-13 11:39
jonthan3417-May-13 11:39 
Questionyou awsome Pin
Dark_traveller9-May-13 0:32
Dark_traveller9-May-13 0:32 
QuestionVisible, not Visable Pin
wizardzz17-Apr-12 8:11
wizardzz17-Apr-12 8:11 
AnswerRe: Visible, not Visable Pin
Narsters17-Apr-12 9:46
Narsters17-Apr-12 9:46 
GeneralMy vote of 4 Pin
ArjunPr21-Sep-11 18:04
ArjunPr21-Sep-11 18:04 
GeneralMy vote of 3 Pin
Member 810932425-Jul-11 1:37
Member 810932425-Jul-11 1:37 
GeneralMy vote of 4 Pin
fyarbasi4-Oct-10 1:07
fyarbasi4-Oct-10 1:07 
QuestionHow to Make Bold in Part of an Excel Cell - Need Eargent help!!!!!!! Pin
supuna2u12-Sep-10 17:16
supuna2u12-Sep-10 17:16 
QuestionOpening an excel workbook from Document Library Pin
suruKarthik30-Mar-10 23:16
suruKarthik30-Mar-10 23:16 
QuestionHow to make it work with Excel 2007 Pin
th3_m0t410-Feb-10 13:48
th3_m0t410-Feb-10 13:48 
AnswerRe: How to make it work with Excel 2007 Pin
Narsters10-Feb-10 18:08
Narsters10-Feb-10 18:08 
GeneralReading Excel Embeded objects Pin
Shrihari Devji7-Jan-10 20:15
Shrihari Devji7-Jan-10 20:15 
GeneralThank you very much Pin
Bidesh Mukherjee25-Nov-09 0:44
professionalBidesh Mukherjee25-Nov-09 0:44 

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

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