Daten in ein Excelsheet schreiben

include <ComObj.hpp> // include-Reihenfolge beachten!!!
include <utilcls.h> 

.
.
.

void __fastcall TForm1::SchreibenClick(TObject *Sender)
{
    Variant Excel;

    try
    {
        Excel = GetActiveOleObject("Excel.Application");
    }
    catch(...)
    {
        Excel = CreateOleObject("Excel.Application");
    }

    //Excel.OlePropertySet("Visible", true); //Excel beim Arbeiten anzeigen, false = ausblenden

    try
    {
        Variant WorkBooks = Excel.OlePropertyGet("WorkBooks");
        WorkBooks.OleFunction("Add");
        Variant ActiveWorkBook = Excel.OlePropertyGet("ActiveWorkbook");
        Variant WorkSheets = Excel.OlePropertyGet("Worksheets");
        Variant WorkSheet = WorkSheets.OlePropertyGet("Item", 1);
        WorkSheet.OleFunction("Activate");

        for (int iRow=0; iRow < 11; iRow++)
        {
            for (int iCol = 0; iCol < 11; iCol++)
            {
                Variant Range = WorkSheet.OlePropertyGet("Cells", iRow+1, iCol+1); // Row=.Zeile / Col=Spalte
                Range.OlePropertySet("Value", "TestText"+IntToStr(iCol)+IntToStr(iRow));
                Application->ProcessMessages();
            }
        }

        ActiveWorkBook.OleFunction("SaveAs", ".QueryResult.xls"); //Datei speichern
    }
    catch(...){}

    ShowMessage("Excel wird jetzt wieder geschlossen");

    Excel.OleFunction("Quit");
    Excel = Unassigned;
}

Schreibe einen Kommentar