简体   繁体   中英

C++ Builder and Excel Automation, where to get started?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM