Adding Excel Functionality To Your Project

Add Microsoft Excel Reference

Menu > Project > Properties > Common Properties > Add Reference > .Net > Microsoft.Office.Interop.Excel (choose the latest version)

Add Namespaces

	using namespace Microsoft::Office::Core;
	//using namespace Microsoft::Office::Interop::Excel;		//To avoid pain with errors due to clashes with "Application" by using this we use the below instead
	using namespace Microsoft::Office::Interop;
Create Object

	private: Excel::Application ^ExcelApp1;

	ExcelApp1 = gcnew Excel::Application();

Reading Cells In A Worksheet


	try
	{
		txtOutput->Text = "";


		//----- OPEN EXCEL WORKBOOK -----
		Excel::Workbook ^WorkBook1 = ExcelApp1->Workbooks->Open("C:\\_Downloaded\\test.xlsx",
													 0,
													 true,
													 5,
													 "",
													 "",
													 true,
													 Excel::XlPlatform::xlWindows,
													 "\t",
													 false,
													 false,
													 0,
													 true,
													 1,
													 0);



		//----- OPEN THE WORKSHEET -----
		/* Use this if you need to deal with workbooks with multiple sheets
		int SheetNumber;
		for (SheetNumber = 1; SheetNumber <= WorkBook1->Sheets->Count; SheetNumber++)
		{
		}
		*/
		Excel::Worksheet ^WorkSheet1 = (Excel::Worksheet^)WorkBook1->ActiveSheet;

		//If you don't know which cells your after you can use this:
		//Excel::Range ^ExcelRange1 = Sheet1->UsedRange;
		

		//----- READ WORKSHEET -----
		int RowIndex = 1;
		int ColumnIndex = 1;
		String ^CellValue;

		for (RowIndex = 1; RowIndex <= 10; RowIndex++)
		{
			//----- READ NEXT ROW -----
			for (ColumnIndex = 1; ColumnIndex <= 3; ColumnIndex++)	
			{
				//----- READ NEXT COLUMN -----
				if (((Excel::Range^)WorkSheet1->Cells[(System::Object^)RowIndex, (System::Object^)ColumnIndex])->Value2 != nullptr)
				{
					//CELL HAS A VALUE
					CellValue = ((Excel::Range^)WorkSheet1->Cells[(System::Object^)RowIndex, (System::Object^)ColumnIndex])->Value2->ToString();
					
					txtOutput->Text += "'" + CellValue + "'";
				}
				else
				{
					//CELL IS BLANK
					txtOutput->Text += "#";
				}
			}
			txtOutput->Text += "\r\n";
		}
	    
		//----- CLOSE WORKBOOK -----
		WorkBook1->Close(false, "C:\\_Downloaded\\test.xlsx", nullptr);


	}
	catch (Exception ^e)
	{
		MessageBox::Show(L"Error:\n" + e, L"Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
	}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.