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: 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!

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