Click here to Skip to main content
15,881,172 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  
Introduction to manipulating Excel with C#.
using System;
using Excel;

namespace ExcelExample
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class ExcelClass
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Excel.Application excelApp = new Excel.ApplicationClass();  // Creates a new Excel Application
			excelApp.Visible = true;  // Makes Excel visible to the user.

			// The following line adds a new workbook
			Excel.Workbook newWorkbook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
			
			// The following code opens an existing workbook
			string workbookPath = "c:/SomeWorkBook.xls";  // Add your own path here
			Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
				false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, 
				false,  0, true, false, false);
			
			// The following gets the Worksheets collection
			Excel.Sheets excelSheets = excelWorkbook.Worksheets;

			// The following gets Sheet1 for editing
			string currentSheet = "Sheet1";
			Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
			
			// The following gets cell A1 for editing
			Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A1", "A1");

			// The following sets cell A1's value to "Hi There"
			excelCell.Value2 = "Hi There";
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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