1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| unit DirtyStringGrid_MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids;
type
TForm1 = class(TForm)
Memo1: TMemo;
StringGrid1: TStringGrid;
Button1: TButton;
Button2: TButton;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
TStringGridTool = record
public
class procedure LoadFromStream(AGrid: TStringGrid; AStream: TStream); static;
class procedure SaveToStream(AGrid: TStringGrid; AStream: TStream); static;
end;
var
Form1: TForm1;
implementation
uses System.Math;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
MS: TMemoryStream;
begin
MS := TMemoryStream.Create();
try
Memo1.Lines.SaveToStream(MS);
MS.Seek(0, soBeginning);
TStringGridTool.LoadFromStream(StringGrid1, MS);
finally
MS.Free();
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
MS: TMemoryStream;
begin
MS := TMemoryStream.Create();
try
TStringGridTool.SaveToStream(StringGrid1, MS);
MS.Seek(0, soBeginning);
Memo2.Lines.LoadFromStream(MS);
finally
MS.Free();
end;
end;
{ TStringGridTool }
class procedure TStringGridTool.LoadFromStream(AGrid: TStringGrid; AStream: TStream);
var
Lines, Header: TStringList;
I: Integer;
begin
Lines := TStringList.Create();
try
Lines.LoadFromStream(AStream);
AGrid.FixedRows := 1; // Header ?
AGrid.RowCount := Lines.Count;
AGrid.FixedCols := 0;
AGrid.ColCount := 0;
if Lines.Count > 0 then
begin
Header := TStringList.Create();
try
Header.Delimiter := ';';
Header.StrictDelimiter := True;
Header.DelimitedText := Lines[0];
AGrid.ColCount := Header.Count;
AGrid.Rows[0].Assign(Header);
finally
Header.Free();
end;
for I := 1 to Lines.Count - 1 do
begin
AGrid.Rows[I].Delimiter := ';';
AGrid.Rows[I].StrictDelimiter := True;
AGrid.Rows[I].DelimitedText := Lines[I];
AGrid.ColCount := Max(AGrid.ColCount, AGrid.Rows[I].Count);
end;
end;
finally
Lines.Free();
end;
end;
class procedure TStringGridTool.SaveToStream(AGrid: TStringGrid; AStream: TStream);
var
Lines: TStringList;
I: Integer;
begin
Lines := TStringList.Create();
try
Lines.Capacity := AGrid.RowCount;
for I := 0 to AGrid.RowCount - 1 do
begin
AGrid.Rows[I].Delimiter := ';';
Lines.Add(AGrid.Rows[I].DelimitedText);
end;
Lines.SaveToStream(AStream);
finally
Lines.Free();
end;
end;
end. |
Partager