Title: Save DataSet As CSV Textfile
Question: How to save the content of a DataSet as a CSV textfile?
Answer:
Easy and quick way to save a dataset as a CSV file. Works with both BDE and DBExpress datasets.
Tip: if you have the data displayed in a grid, set the DBGrid1.Enabled to false before calling the SaveAsCSV procedure, otherwise the procedure will be as slow as your screen display...
*************************************************************
procedure btnSaveClick(Sender: TObject);
begin
DBGrid1.Visible := False;
try
if (SaveDialog1.Execute = true) and
(length(SaveDialog1.FileName) 0) then
begin
SaveDialog1.DefaultExt := 'CSV';
SaveAsCSV(SaveDialog1.FileName,ClientDataSet1);
end;
finally
DBGrid1.Visible := True;
end;
end;
*************************************************************
procedure SaveAsCSV(myFileName: string; myDataSet: TDataSet);
var
myTextFile: TextFile;
i: integer;
s: string;
begin
//create a new file
AssignFile(myTextFile, myFileName);
Rewrite(myTextFile);
s := ''; //initialize empty string
try
//write field names (as column headers)
for i := 0 to myDataSet.FieldCount - 1 do
begin
s := s + Format('"%s";', [myDataSet.Fields[i].FieldName]);
end;
Writeln(myTextFile, s);
//write field values
while not myDataSet.Eof do
begin
s := '';
for i := 0 to myDataSet.FieldCount - 1 do
begin
s := s + Format('"%s";', [myDataSet.Fields[i].AsString]);
end;
Writeln(myTextfile, s);
myDataSet.Next;
end;
finally
CloseFile(myTextFile);
end;
end;
*************************************************************