// SaveGridToFile method by KodeZwerg for FreePascal forum
// this method can plain save grid content into a text file where each element is seperated by a delimiter (default = ",")
// argument #1: the stringgrid that you want to save
// argument #2: the filepath and filename to save, no checking if valid
// argument #3: optional set a delimiter, default ","
// argument #4: optional shall the save include fixed cells, default False
// argument #5: optional shall the save include the title cells, default False
procedure SaveGridToFile(const AStringGrid: TStringGrid; const AFileName: string; const ADelimiter: Char = ','; const AIncludeFixed: Boolean = False; const AIncludeTitle: Boolean = False);
var
LRow, LCol, // where are we inside loop
LRowStart, LColStart: Integer; // where do we start working at
sl, hl: TStringList; // sl is the main list with formated results from hl
begin
sl := TStringList.Create; // create object, needed in the main loop
try
hl := TStringList.Create; // create object, needed in the main loop to create the sl list
try
hl.Delimiter := ADelimiter; // setup Delimiter
hl.StrictDelimiter := False; //force quoting of strings that contain whitespace or Delimiter
if AIncludeFixed then // user wants to include the fixed cells in the results
begin
if AIncludeTitle then // user wants to include the title
LRowStart := 0 // giving every row
else
if ((AStringGrid.FixedRows >= 1) and (AStringGrid.RowCount > 0)) then // giving fixed row without title
LRowStart := 1 // we cut the title off
else
LRowStart := 0; // giving all
LColStart := 0; // 0 for the fixed beginning
end // user wants to include the fixed cells in the results
else
begin // user does not want to have fixed cells
if AIncludeTitle then // user wants to include title (what results in getting all cells)
LRowStart := 0 // giving all
else
LRowStart := AStringGrid.FixedRows; // user want no fixed row data
LColStart := AStringGrid.FixedCols; // user want no fixed col data
end; // user does not want to have fixed cells
for LRow := LRowStart to Pred(AStringGrid.RowCount) do // begin outer loop for the rows
begin
hl.Clear; // clear stringlist
for LCol := LColStart to Pred(AStringGrid.ColCount) do // begin inner loop for the columns
hl.Add(AStringGrid.Cells[LCol, LRow]); // transport string-grid-cell to stringlist
sl.Add(hl.DelimitedText); // store the generated delimited
end;
finally
hl.Free; // free the hl list
end;
if (sl.Count > 0) then // we gathered something, lets save
sl.SaveToFile(AFilename, True); // save main list to disk
// this method assume that you want to save and overwrite
// so check outside of this method your filename on disk etc...
finally
sl.Free; // free the main list
end;
end;