function DataSetToExcelSheet(ADataSet: TDataSet; AFieldTagMax: Integer; ASheet: OleVariant): Boolean;
var
Row, Col, FieldIndex: Integer;
BookMark: TBookMark;
begin
if ADataSet.Active then
begin
BookMark:= ADataSet.GetBookMark;
ADataSet.DisableControls;
ASheet.Activate;
try
//工作表单的列标题
Row:= 1;
Col:= 1;
for FieldIndex:= 0 to ADataSet.FieldCount - 1 do
begin
if ADataSet.Fields[FieldIndex].Tag <= AFieldTagMax then
begin
ASheet.Cells(Row, Col):= ADataSet.Fields[FieldIndex].DisplayLabel;
Inc(Col);
end;
end;
//工作表单的内容
ADataSet.First;
while Not ADataSet.Eof do
begin
Row:= Row + 1;
Col:= 1;
for FieldIndex:= 0 to ADataSet.FieldCount - 1 do
begin
if ADataSet.Fields[FieldIndex].Tag <= AFieldTagMax then
begin
ASheet.Cells(Row, Col):= ADataSet.Fields[FieldIndex].AsString;
Inc(Col);
end;
end;
ADataSet.Next;
end;
Result:= True;
finally
ADataSet.GotoBookMark(BookMark);
ADataSet.EnableControls;
end;
end
else
Result:= False;
end;
function DataSetToExcel(ADataSet: TDataSet; AFieldTagMax: Integer; AVisible: Boolean; AExcelFileName: String = ''): Boolean;
var
ExcelObj, Excel, WorkBook, Sheet: OleVariant;
SaveDialog: TSaveDialog;
begin
if ADataset.Active then
begin
ExcelObj:= CreateOleObject('Excel.Sheet');
try
Excel:= ExcelObj.Application;
Excel.Visible:= AVisible ;
WorkBook:= Excel.WorkBooks.Add;
Sheet:= WorkBook.Sheets[1];
if DataSetToExcelSheet(ADataSet, AFieldTagMax, Sheet) then
begin
if AExcelFileName <> '' then
begin
WorkBook.SaveAs(FileName:= AExcelFileName);
Result:= True;
end
else
begin
SaveDialog:= TSaveDialog.Create(Nil);
try
SaveDialog.Filter:= 'Microsoft Excel 文件|*.xls';
if SaveDialog.Execute then
begin
WorkBook.SaveAs(FileName:= SaveDialog.FileName);
Result:= True;
end
else
Result:= False;
UpdateWindow(GetActiveWindow);
finally
SaveDialog.Free;
end;
end;
end
else
Result:= False;
finally
Excel.Quit;
end;
end
else
Result:= False;
end;