Author: Zswang Wangjihu
1 ///////Begin Source
2
3 function StrLeft(const mStr: string; mDelimiter: string): string;
4 begin
5 Result := Copy(mStr, 1, Pos(mDelimiter, mStr) - 1);
6 end; { StrLeft }
7
8 function ListCount(mList: string; mDelimiter: string = ','): Integer;
9 var
10 I, L: Integer;
11 begin
12 Result := 0;
13 if mList = '' then
14 Exit;
15 L := Length(mList);
16 I := Pos(mDelimiter, mList);
17 while I > 0 do
18 begin
19 mList := Copy(mList, I + Length(mDelimiter), L);
20 I := Pos(mDelimiter, mList);
21 Inc(Result);
22 end;
23 Inc(Result);
24 end; { ListCount }
25
26 function ListValue(mList: string; mIndex: Integer; mDelimiter: string = ','):
27 string;
28 var
29 I, L, K: Integer;
30 begin
31 L := Length(mList);
32 I := Pos(mDelimiter, mList);
33 K := 0;
34 Result := '';
35 while (I > 0) and (K <> mIndex) do
36 begin
37 mList := Copy(mList, I + Length(mDelimiter), L);
38 I := Pos(mDelimiter, mList);
39 Inc(K);
40 end;
41 if K = mIndex then
42 Result := StrLeft(mList + mDelimiter, mDelimiter);
43 end; { ListValue }
44
45 function DataSetToText(mDataSet: TDataSet; mStrings: TStrings;
46 mDelimiter: string = #9): Boolean;
47 var
48 vBookmark: string;
49 I: Integer;
50 S: string;
51 begin
52 Result := False;
53 if (not Assigned(mDataSet)) or (not mDataSet.Active) or
54 (not Assigned(mStrings)) then
55 Exit;
56 mStrings.Text :=
57 StringReplace(Trim(mDataSet.FieldList.Text), #13#10, mDelimiter,
58 [rfReplaceAll]);
59 vBookmark := mDataSet.Bookmark;
60 mDataSet.DisableControls;
61 try
62 mDataSet.First;
63 while not mDataSet.Eof do
64 begin
65 S := '';
66 for I := 0 to mDataSet.FieldList.Count - 1 do
67 S := S + mDelimiter + mDataSet.FieldList[I].AsString;
68 Delete(S, 1, Length(mDelimiter));
69 mStrings.Add(S);
70 mDataSet.Next;
71 end;
72 finally
73 mDataSet.Bookmark := vBookmark;
74 mDataSet.EnableControls;
75 end;
76 Result := True;
77 end; { DataSetToText }
78
79 function TextToDataSet(mStrings: TStrings; mDataSet: TDataSet;
80 mDelimiter: string = #9): Boolean;
81 var
82 I, J, C: Integer;
83 vFieldNames: string;
84 begin
85 Result := False;
86 if (not Assigned(mDataSet)) or (not mDataSet.Active) or
87 (mStrings.Count <= 0) then
88 Exit;
89 vFieldNames := mStrings[0];
90 C := ListCount(vFieldNames, mDelimiter);
91 for I := 1 to mStrings.Count - 1 do
92 try
93 mDataSet.Append;
94 for J := 0 to C - 1 do
95 if mDataSet.FieldList.IndexOf(ListValue(vFieldNames, J, mDelimiter)) >= 0 then
96 mDataSet[ListValue(vFieldNames, J, mDelimiter)] :=
97 ListValue(mStrings[I], J, mDelimiter);
98 mDataSet.Post;
99 except
100 Exit;
101 end;
102 Result := True;
103 end; { TextToDataSet }
104 ///////End Source
105
106 ///////Begin Demo
107
108 procedure TForm1.Button1Click(Sender: TObject);
109 begin
110 DataSetToText(Table1, Memo1.Lines);
111 end;
112
113 procedure TForm1.Button2Click(Sender: TObject);
114 begin
115 TextToDataSet(Memo1.Lines, Table1);
116 end;
117 ///////End Demo
|