龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

如何在C++中将数据库数据分行和列保存到Excel中

时间:2009-12-22 15:42来源:未知 作者:admin 点击:
分享到:
如何在C++中将数据库数据分行和列保存到Excel中? 程序中的数据在StringGrid控件中显示的,那如何按照StringGrid显示的格式分行分列保存到Excel表格呢?请看如下两种方法的实现: 第一种

  如何在C++中将数据库数据分行和列保存到Excel中? 程序中的数据在StringGrid控件中显示的,那如何按照StringGrid显示的格式分行分列保存到Excel表格呢?请看如下两种方法的实现:

   第一种方法:采用的一格一格填充数据

 Variant ExcelApp,WorkBook1,WorkSheet1;

//---------------------------------------------------------------------------

__fastcall TForm1::TForm1(TComponent* Owner)

    : TForm(Owner)

{

}

//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)

{

   AnsiString FileName = ExtractFileDir(Application->ExeName )+  "a.xls";

   try

    {

       ExcelApp=Variant::CreateObject("Excel.Application");

    }

    catch(...)

    {

       ShowMessage("Sorry!Excel cannot be launched");

       return;

    }

    ExcelApp.OlePropertySet("Visible",true);

    ExcelApp.OlePropertyGet("WorkBooks").OleProcedure("Open",FileName.c_str());

    WorkBook1=ExcelApp.OlePropertyGet("ActiveWorkBook");

    WorkSheet1=WorkBook1.OlePropertyGet("ActiveSheet");

    for(int i=0;iRowCount;i++)

    {

        for(int j=0;jColCount;j++)

        {

            WorkSheet1.OlePropertyGet("Cells", i+1 , j+1 )

                             .OlePropertySet("Value",StringGrid1->Cells[j][i].c_str() ) ;

        }

    }

    ExcelApp.OlePropertyGet("ActiveWorkbook")

            .OleFunction("SaveAs", FileName.c_str());

    ExcelApp.OleFunction("Quit");

    WorkSheet1 = Unassigned;

    WorkBook1 = Unassigned;

    ExcelApp = Unassigned;

}

精彩图集

赞助商链接