Daniel Duffy
C++ author, trainer
- Joined
- 10/4/07
- Messages
- 10,431
- Points
- 648
Code:
// ExcelHelloWorld.cpp
//
// (C) Datasim Education BV 2012
//
#include <string>
#include <iostream>
// Office 2003 (Office v11) (Will give error (actually a warning) that you need W2K or higher to run the result)
/*#import "C:\Program Files\Common Files\Microsoft Shared\office11\mso.dll" rename("DocumentProperties", "DocumentPropertiesXL") rename("RGB", "RBGXL")
#import "C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\vbe6ext.olb"
#import "C:\Program Files\Microsoft Office\Office11\EXCEL.EXE" rename("DialogBox", "DialogBoxXL") rename("RGB", "RBGXL") rename("DocumentProperties", "DocumentPropertiesXL") rename("ReplaceText", "ReplaceTextXL") rename("CopyFile", "CopyFileXL") no_dual_interfaces
*/
// Excel 2010
#import "C:\Program Files\Common Files\Microsoft Shared\office14\mso.dll" rename("DocumentProperties", "DocumentPropertiesXL") rename("RGB", "RGBXL")
#import "C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\vbe6ext.olb"
#import "C:\Program Files\Microsoft Office\Office14\EXCEL.EXE" rename("DialogBox", "DialogBoxXL") rename("RGB", "RGBXL") rename("DocumentProperties", "DocumentPropertiesXL") rename("ReplaceText", "ReplaceTextXL") rename("CopyFile", "CopyFileXL") no_dual_interfaces
// Other versions here
#include "atlsafe.h" // Data types
// Extract a value from a cell
double GetDoubleFromCell(Excel::_WorksheetPtr sheet, CComBSTR cell)
{
Excel::RangePtr range=sheet->GetRange(CComVariant(cell));
_variant_t value=range->GetValue2();
return value;
}
// Put a double value in an Excel cell
void SetCellValue(Excel::_WorksheetPtr sheet, CComBSTR cell, double value)
{
Excel::RangePtr range=sheet->GetRange(CComVariant(cell));
range->Value2=value;
}
int main()
{
Excel::_ApplicationPtr xl; // Pointer to Excel.
try
{
// Initialize COM Runtime Libraries.
CoInitialize(NULL);
// Start excel application.
xl.CreateInstance(L"Excel.Application");
xl->Visible = VARIANT_TRUE;
xl->Workbooks->Add((long) Excel::xlWorksheet);
// Rename "Sheet1" to "Chart Data".
Excel::_WorkbookPtr workbook = xl->ActiveWorkbook;
//Excel::_WorksheetPtr sheet = workbook->Worksheets->GetItem("Sheet1");
Excel::_WorksheetPtr sheet = workbook->Worksheets->GetItem(1); //Language-independent
sheet->Name = "Chart Data";
// Get the parameters
double T=GetDoubleFromCell(sheet, "B2");
double r=GetDoubleFromCell(sheet, "B3");
double val = 2.0;
// Display values in Excel
SetCellValue(sheet, "B9", val);
SetCellValue(sheet, "B10", val*3);
}
catch( _com_error & error )
{
bstr_t description = error.Description();
if( !description )
{
description = error.ErrorMessage();
}
std::cout << std::string(description);
}
CoUninitialize();
return 0;
}
Compile and link the project.
Does it run?