Export TDataSet

This code exports the contents of TDataSet to a worksheet.
uses
  {...}, OExport, OExport_Vcl;

procedure DatasetToExcel(const aDS: TDataSet; const aFileName: string);
var
  xExport: TOExport;
  xWS: TExportWorkSheet;
  xRow: TExportRow;
  I: Integer;
  xField: TField;
begin
  xExport := TOExport.Create;
  try
    xWS := xExport.AddWorkSheet(\'data\');
    xRow := xWS.AddRow;
    for I := 0 to aDS.FieldCount-1 do
      xRow.AddCellString(aDS.Fields[I].FieldName).SetFontStyle([fsBold]);

    aDS.First;
    while not aDS.EOF do
    begin
      xRow := xWS.AddRow;
      for I := 0 to aDS.FieldCount-1 do
      begin
        xField := aDS.Fields[I];
        case xField.DataType of
          ftSmallint, ftInteger, ftWord, ftLargeint:
            xRow.AddCellNumber(xField.AsInteger, 0);
          ftFloat, ftCurrency, ftBCD, ftFMTBcd:
            xRow.AddCellNumber(xField.AsInteger, 0);
          ftBoolean:
            xRow.AddCellBoolean(xField.AsBoolean);
          ftDate:
            xRow.AddCellDate(xField.AsDateTime);
          ftTime:
            xRow.AddCellTime(xField.AsDateTime);
          ftDateTime, ftTimeStamp:
            xRow.AddCellDateTime(xField.AsDateTime);
        else
          xRow.AddCellString(xField.AsString);
        end;
      end;
      aDS.Next;
    end;

    xExport.SaveToFile(aFileName);
  finally
    xExport.Free;
  end;
end;
Categories