|
/*************************************************************************** //将数据集得数据导出到Excel; //void DataSetToExcel(TDataSet* DataSet,bool DisplayByRow); // DisplayByRow:表按行排(正常) //最后修改时间 2004-5-25 ****************************************************************************/
代码: void DataSetToExcel(TDataSet* DataSet,bool DisplayByRow) { //#define Excel_Test Variant Ex,Wbs,Wb,Sh1; Screen->Cursor = crHourGlass ; if(Ex.IsEmpty()) #ifdef Excel_Test try { Ex = Variant::CreateObject("Excel.Application"); // Wbs = (Ex.OlePropertyGet("Workbooks")).OleFunction("Add");//新建一新工作薄 // Sh1 = Wbs.OlePropertyGet("ActiveSheet"); } #else try { HWND hPrevApp = ::FindWindow(NULL,"Microsoft Excel"); if(hPrevApp == NULL) // 如果没有找到已经打开的 Excel 活动窗口 { Ex = Variant::CreateObject("Excel.Application"); //启动Excel } else { Ex = Variant::GetActiveObject("Excel.Application"); } } #endif catch(...) { Screen->Cursor=crDefault; ShowMessage("打开Excel出错,请确认你已经正确安装了MS Office!"); return; } try { // if(Ex.OlePropertyGet("ActiveWorkBook").IsEmpty()) // 如果当前没有活动的工作薄 { Ex.OlePropertyGet("WorkBooks").OleProcedure("ADD"); //新建一新工作薄 } if(Wb.IsEmpty()) { Wb=Ex.OlePropertyGet("ActiveWorkBook"); } Sh1 = Wb.OlePropertyGet("ActiveSheet");
Sh1.OlePropertyGet("Cells").OlePropertyGet("Font").OlePropertySet("Size",10); } catch(...) { Ex = Ex.Empty(); Wb = Wb.Empty(); DataSetToExcel(DataSet, DisplayByRow); }
if(DisplayByRow) { int CurrCol = 0; for (int j=0; j<DataSet->Fields->Count; j++) { if(DataSet->Fields->Fields[j]->Visible) { CurrCol++; Sh1.OlePropertyGet("Cells", 1, CurrCol).OlePropertySet( "value",DataSet->Fields->Fields[j]->FieldName.c_str()); Sh1.OlePropertyGet("Cells", 1, CurrCol).OlePropertyGet("Font").OlePropertySet("Bold",true); } } DataSet->First(); int i = 0; while(!DataSet->Eof) { CurrCol=0; for (int j=0; j<DataSet->Fields->Count; j++) { if(DataSet->Fields->Fields[j]->Visible) { CurrCol++; Sh1.OlePropertyGet("Cells", i+2, CurrCol).OlePropertySet( "value", DataSet->Fields->Fields[j]->AsString.c_str()); } } Application->ProcessMessages(); DataSet->Next(); i++; } } else { int CurrRow = 0; for (int j=0; j<DataSet->Fields->Count; j++) { if(DataSet->Fields->Fields[j]->Visible) { CurrRow++ ; Sh1.OlePropertyGet("Cells", CurrRow, 1).OlePropertySet( "value", DataSet->Fields->Fields[j]->FieldName.c_str()); DataSet->First(); int i=0; while(!DataSet->Eof) { Sh1.OlePropertyGet("Cells",CurrRow,i+2).OlePropertySet( "value", DataSet->Fields->Fields[j]->AsString.c_str()); Application->ProcessMessages(); DataSet->Next(); i++; } } } } Ex.OlePropertySet("Visible", (Variant)true); //使Excel启动后可见 Screen->Cursor=crDefault; } //----------------------------------------------------------------------------
代码: void ExportToExcelTest() { TADODataSet * adoTemp = new TADODataSet(NULL); adoTemp->Connection = ADODataSet1->Connection;//可以是其他连接 adoTemp->Active = false; adoTemp->CommandText = "Select * From test"; adoTemp->Active = true; DataSetToExcel(adoTemp, true); delete adoTemp; } |