三、实现将界面中选中的记录导出到Excel(tabTestResults)中
/**************************************************************************
Function: OutputAsEXCELClick
Description: 实现将结果查询界面中选中的记录导出到Excel(tabTestResults)中
Editor:wt
Time:2008-09-02
/**************************************************************************/
void __fastcall TTestResultForm::OutputAsEXCELClick(TObject *Sender)
{
DModule->ADOQueryTmp->Close();
DModule->ADOQueryTmp->SQL->Clear();
DModule->ADOQueryTmp->SQL->Add("Select * from tabTestResults where IsbPrint=1");
DModule->ADOQueryTmp->Open();
DModule->ADOQueryTmp->First();
if(DModule->ADOQueryTmp->RecordCount>=0)
{
if(DModule->ADOQueryTmp->RecordCount==0)
{
Application->MessageBox("没有找到分合信息,请正确选择分合信息!","信息提示",MB_ICONASTERISK+MB_OK); return;
}
if(!resultQueryGrid->DataSource->DataSet->Active) // 数据集没有打开就返回
return;
Variant vExcelApp, vSheet;
AnsiString strXlsFile;
// 设置保存路径
strXlsFile=AppPath+"tabTestResults" ;
try
{
vExcelApp = Variant::CreateObject("Excel.Application");
}
catch(...)
{
MessageBox(0, "启动 Excel 出错, 可能是没有安装Excel.","DBGrid2Excel", MB_OK | MB_ICONERROR);
return;
}
// 隐藏Excel界面
vExcelApp.OlePropertySet("Visible", false);
// 新建一个工作表
vExcelApp.OlePropertyGet("Workbooks").OleFunction("Add", 1); // 工作表
// 操作这个工作表
vSheet = vExcelApp.OlePropertyGet("ActiveWorkbook").OlePropertyGet("Sheets", 1);
//表格的行数
int nRowCount(resultQueryGrid->DataSource->DataSet->RecordCount + 1);
nRowCount = nRowCount < 2? 2: nRowCount;
// 表格的列数
int nColCount(resultQueryGrid->Columns->Count);
nColCount = nColCount < 1? 1: nColCount;
// 设置单元格的宽度
for(int i=0; i<nColCount; i++)
{
int nColWidth = resultQueryGrid->Columns->Items[i]->Width;
vExcelApp.OlePropertyGet("Columns", i + 1).OlePropertySet("ColumnWidth", nColWidth / 7);
}
// 先将列名写入Excel表格
for(int j=0; j<resultQueryGrid->Columns->Count; j++)
{
// 标题行的行高
vExcelApp.OlePropertyGet("Rows", 1).OlePropertySet("RowHeight", 20);
vSheet.OlePropertyGet("Cells", 1, j + 1).OlePropertySet("Value",resultQueryGrid->Columns->Items[j]->FieldName.c_str());
}
// 将DBGrid中的数据写入Excel表格
resultQueryGrid->DataSource->DataSet->First();
int k=1;
for(int i=0; i<nRowCount; i++)
{
if(resultQueryGrid->SelectedField->AsBoolean == true)
{ // 普通数据行的行高16
vExcelApp.OlePropertyGet("Rows", i + 2).OlePropertySet("RowHeight", 16);
for(int j=0; j<resultQueryGrid->Columns->Count; j++)
{
vSheet.OlePropertyGet("Cells", k + 1, j + 1).OlePropertySet("Value",resultQueryGrid->DataSource->DataSet->FieldByName(resultQueryGrid->Columns->Items[j]->FieldName)->AsString.c_str());
}
k++;
}
resultQueryGrid->DataSource->DataSet->Next();
}
// 保存Excel文档并退出
vExcelApp.OlePropertyGet("ActiveWorkbook").OleFunction("SaveAs", strXlsFile.c_str());
vExcelApp.OleFunction("Quit");
vSheet = Unassigned;
vExcelApp = Unassigned;
// 工作结束
MessageBox(0, "选中数据导出成功!", "提示信息", MB_OK | MB_ICONINFORMATION);
}
}