C++ Builder 将数据库数据导出到Excel中总结2

void __fastcall TFrmDispatchDataExport::DisplayExcelReport(String _title, String _strSql)
{
 int i=0;
 Variant ExcelApp1,WorkBook1,Sheet1;
 AnsiString FileName=GetCurrentDir();
 FileName=FileName+"\\Template\\DispatchReport.xlt";
 // run excel
 try
 {
  ExcelApp1=CreateOleObject("Excel.Application"); //启动Excel
 }
 catch(...)
 {
  ShowMessage("Can not start excel");
  return;
 }

 // open InOrderTo.xlt
 ExcelApp1.OlePropertySet("Visible",(Variant)false);
 ExcelApp1.OlePropertyGet("WorkBooks").OleFunction("Add",(WideString)FileName.c_str());
 WorkBook1=ExcelApp1.OlePropertyGet("ActiveWorkBook");
 Sheet1=WorkBook1.OlePropertyGet("ActiveSheet");
 String Str_Title="";
 Str_Title=Str_Title+"                        "+_title;

 // print Inordermst info
 Sheet1.OlePropertyGet("Cells",1,6).OlePropertySet("Value",(WideString)Str_Title);
// Sheet1.OlePropertyGet("Cells",3,7).OlePropertySet("Value",FrmMain->UserParameters->GetOperatorID().c_str());
// Sheet1.OlePropertyGet("Cells",3,9).OlePropertySet("Value",FrmMain->GetSysDateTime().DateTimeString().c_str());


 // print InOrderdtl info
 qryExport->Close();
 qryExport->SQL->Clear();
 qryExport->SQL->Add(_strSql);
 qryExport->Open();
 qryExport->First();

 int nPos = 0;
 int nStep  = 0;
 int nRecordCnt = qryExport->RecordCount;
 if ( nRecordCnt > 0 )
 {
  nStep = ceil(nRecordCnt/100.0);
  pbExport->StepBy(1);
 }
 statOARBar->Panels->Items[1]->Text = IntToStr(nRecordCnt) ;
 int iRows = 0;
 for(iRows=6;iRows < qryExport->RecordCount+6;iRows++)
 {
  if( bIsStop ){break;}
  Sheet1.OlePropertyGet("Rows",iRows+1).OleProcedure("Insert");
  Sheet1.OlePropertyGet("Cells",iRows,1).OlePropertySet("Value",iRows-5);
  for(int iCols = 1;iCols < qryExport->FieldCount;iCols++)
  {
   if( bIsStop ){break;}
   String strValue = qryExport->Fields->Fields[iCols-1]->AsString.Trim();
   Sheet1.OlePropertyGet("Cells",iRows,iCols+1).OlePropertySet("Value",(WideString)strValue);
  }
  ++nPos;
  if ( nPos%nStep == 0 )
  {
   pbExport->StepIt();
   Application->ProcessMessages();
  }
  qryExport->Next();
 }
 Sheet1.OlePropertyGet("Rows",iRows).OleProcedure("Delete");
 Sheet1.OlePropertyGet("Rows",iRows).OleProcedure("Delete");
 ExcelApp1.OlePropertySet("Visible",(Variant)true);
}

 

备注:需要一个模板文件:DispatchReport.xlt   ,该段代码是将创建的Excel默认是不显示的,当你操作完成后,会显示,这样你可以手动保存或者不保存。由用户决定,我个人认为这个比较好一些,代码清晰而且简单。希望大家有不清楚的地方和我联系:QQ:1574203887 或者邮箱:chao_song2011@sina.cn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值