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);
}
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.
11 years ago
perfect, at last, only place on the internet to mention the clash of Microsoft::Office::Interop::Excel; wasted half a day because of it. cheers