How to export dataset to csv, xls

unit Export2CSV_XLS;

{
  ExportDataset2CSV : Export Dataset to CSV format
  ExportDataset2XLS : Export Dataset to Ms. Excel format
}
interface

uses DB;

procedure ExportDataset2CSV(DataSet: TDataSet; FileName: string);
procedure ExportDataset2XLS(DataSet: TDataSet; FileName: string);

implementation

uses Classes, ComObj;

procedure ExportDataset2CSV(DataSet: TDataSet; FileName: string);
var
  List: TStringList;
  S: String;
  i: integer;
begin
  List := TStringList.Create;
  try
    DataSet.DisableControls;
    DataSet.First;
    List.Add('sep=;');
    while not DataSet.Eof do
    begin
      S := '';
      for i := 0 to DataSet.FieldCount - 1 do
      begin
        if S > '' then
          S := S + ';';
        S := S + '"' + DataSet.Fields[i].AsString + '"';
      end;
      List.Add(S);
      DataSet.Next;
    end;
  finally
    List.SaveToFile(FileName);
    List.free;
    DataSet.EnableControls;
  end;
end;


procedure ExportDataset2XLS(DataSet: TDataSet; FileName: string);
var
  ExcApp: OleVariant;
  i, l: integer;
begin
  ExcApp := CreateOleObject('Excel.Application');
  ExcApp.Visible := True;
  ExcApp.WorkBooks.Add;
  DataSet.First;
  l := 2;
  DataSet.First;
  for i := 0 to DataSet.Fields.Count - 1 do
    ExcApp.WorkBooks[1].Sheets[1].Cells[1, i + 1] := DataSet.Fields[i]
      .FieldName;
  try
    DataSet.DisableControls;
    while not DataSet.Eof do
    begin
      for i := 0 to DataSet.Fields.Count - 1 do
        ExcApp.WorkBooks[1].Sheets[1].Cells[l, i + 1] :=
          DataSet.Fields[i].DisplayText;
      DataSet.Next;
      l := l + 1;
    end;
    ExcApp.WorkBooks[1].SaveAs(FileName);
  finally
    DataSet.EnableControls;
  end;
end;

end.

Comments