// SAVE StringGrid TO TXT
procedure SAVEStringGridTXT(StringGrid1: TStringGrid);
var
varScoreBestandsnaam: String;
varCellLen: Integer;
varLijn: String;
varRow: Integer;
varCol: Integer;
varFile1: TextFile;
tmpValue: Single;
tmpColCountArr: array of Integer; // col length array
PageWidth: Integer;
begin
// Show vertical and horizontal lines
StringGrid1.Options := StringGrid1.Options + [goVertLine, goHorzLine];
// Adjust column widths automatically
StringGrid1.AutoSizeColumns;
// Check max length for each column
if StringGrid1.ColCount > 0 then
SetLength(tmpColCountArr, StringGrid1.ColCount)
else
raise Exception.Create('PROBLEM !');
for varCol := 0 to StringGrid1.ColCount - 1 do
begin
for varRow := 0 to StringGrid1.RowCount - 1 do
begin
varCellLen := Length(StringGrid1.Cells[varCol, varRow]);
if varRow = 0 then
tmpColCountArr[varCol] := varCellLen
else if tmpColCountArr[varCol] < varCellLen then
tmpColCountArr[varCol] := varCellLen;
end;
end;
// Calculate page width
PageWidth := 0;
for varCol := 0 to High(tmpColCountArr) do
PageWidth := PageWidth + tmpColCountArr[varCol] + 3; // Kolombreedtes + spaties
PageWidth := PageWidth + 2; // For the lines at the beginning/end of each row
varScoreBestandsnaam := 'WIEZEN.txt';
// Write to the file
AssignFile(varFile1, varScoreBestandsnaam);
try
Rewrite(varFile1);
// Write headline
varLijn := StringOfChar(' ', (PageWidth - Length('WIEZEN.txt')) div 2) + 'WIEZEN.txt';
Writeln(varFile1, varLijn);
Writeln(varFile1, StringOfChar('-', PageWidth));
Writeln(varFile1, 'Resultaat Wiezen - ' + FormatDateTime('dd/mm/yyyy HH:nn', Now));
Writeln(varFile1, StringOfChar('-', PageWidth));
// Write data
for varRow := 0 to StringGrid1.RowCount - 1 do
begin
varLijn := '|';
for varCol := 0 to StringGrid1.ColCount - 1 do
begin
if TryStrToFloat(StringGrid1.Cells[varCol, varRow], tmpValue) then
// Align numerical values to the "right"
varLijn := varLijn + ' ' + Format('%' + IntToStr(tmpColCountArr[varCol]) +
's', [FormatFloat('0.####', tmpValue)]) + ' |'
else
// Align text values to the "right"
varLijn := varLijn + ' ' + Format('%' + IntToStr(tmpColCountArr[varCol]) +
's', [StringGrid1.Cells[varCol, varRow]]) + ' |';
end;
Writeln(varFile1, varLijn);
end;
// Footer writing
Writeln(varFile1, StringOfChar('-', PageWidth));
finally
CloseFile(varFile1);
end;
end;
*****************************
// SAVE the files "txt" and "xlsx".
procedure TFmain.SBUTTONSAVEClick(Sender: TObject);
begin
SAVEStringGridTXT(StringGrid1); //execute procedure
end;