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;
{
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!