views:

277

answers:

1

I want to dynamically create and populate an excel spreadsheet with C++ builder 2009, but I'm not entirely sure how to go about it. Searching the web, I've narrowed it down to using OLE Automation. Moreover, I'm looking for a document or programming tutorial that can get me started. Is there a simple programming tutorial that also thoroughly explains the concepts of OLE automation?

A: 

To open an excel spreadsheet:

Variant excelApp = Unassigned;

//EOleSysError is thrown if GetActiveObject does not succeed. i.e
//if Excel is not currently open.
try
{
    excelApp = Variant::GetActiveObject("Excel.Application");
}
catch(EOleSysError& e)
{
    excelApp = Variant::CreateObject("Excel.Application"); //open excel
}

excelApp.OlePropertySet("ScreenUpdating", true);

To get the current cell pointer:

Variant excelCell = excelSheet.OlePropertyGet("Cells"); 

To add values to excel:

// create a vararray of 5 elements starting at 0
int bounds[2] = {0, 4};
Variant variantValues = VarArrayCreate(bounds, 1, varVariant);

variantValues.PutElement(5, 0);
variantValues.PutElement(5, 1);
variantValues.PutElement(5, 2);
variantValues.PutElement(5, 3);
variantValues.PutElement(5, 4);

Variant cellRange = excelCell.OlePropertyGet(
    "Range", 
    excelCell.OlePropertyGet("Item", rowindex, columnindex),  // start cell  
    excelCell.OlePropertyGet("Item", rowindex2, columnindex2) // finishing cell   
    );

// place array into excel
cellRange.OlePropertySet(
    "Value", 
    excelApp.OleFunction("Transpose", variantValues)
    );

I hope this gets you started, you will probably need to include vcl.h and comobj.hpp.

Seth
Thanks for your answer.
WindsurferOak