Jump to content


Photo

Excel compatible SaveToCsv


  • Please log in to reply
No replies to this topic

#1 wvd_vegt

wvd_vegt

    Master Member

  • Honorable Members
  • PipPipPipPipPip
  • 710 posts
  • Gender:Male
  • Location:the Netherlands

Posted 18 March 2005 - 10:46 PM

Hi all,

Here is a routine that saves a grid (and optionally it's header) to a Excel compatible csv file.

CODE
procedure TForm1.ExportToCsv(const GridView: TGridView; const fn: string; const header: Boolean = True);

{

normalcol;"colwithlistseparator;";"colwithquote"""

1;2;5

4;3;6

}

var

 r, c              : Integer;

 sl                : TStringList;

 s                 : string;



 function EscapeSeparator(const value: string): string;

 begin

   if (Pos('"', value) > 0) then

     Result := StringReplace(value, '"', '""', [rfReplaceAll])

   else

     Result := value;



   if (Pos(ListSeparator, Result) > 0) or (Pos('""', Result) > 0) then

     Result := '"' + Result + '"'

 end;



begin

 sl := TStringList.Create;



 if header then

   begin

     s := '';

     for c := 0 to Pred(GridView.Columns.Count) do

       begin

         if c <> 0 then

           s := s + ListSeparator + EscapeSeparator(GridView.Columns[c].Header.Caption)

         else

           s := EscapeSeparator(GridView.Columns[c].Header.Caption);

       end;

     sl.Add(s);

   end;



 for r := 0 to Pred(GridView.RowCount) do

   begin

     s := '';

     for c := 0 to Pred(GridView.Columns.Count) do

       begin

         if c <> 0 then

           s := s + ListSeparator + EscapeSeparator(GridView.Cell[c, r].AsString)

         else

           s := EscapeSeparator(GridView.Cell[c, r].AsString);

       end;

     sl.Add(s);

   end;



 sl.SaveToFile(fn);

 sl.Free;

end;


Have fun coding!
G.W. van der Vegt




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users