Registriert seit: 27. Feb 2019
77 Beiträge
|
AW: csv Datei Import ClassHelper für TClientDataSet
21. Mai 2019, 21:49
@Schokohase
Ich bin ja froh das deine Datei auch nicht die Anforderung erfüllt
Zitat von Schokohase:
Meine Testdaten
Delphi-Quellcode:
'a;b;c;d' + sLineBreak +
'a;"b;b";"c'#10'c";d'
mit dieser Version wird aber auch deine Datei eingelesen
Delphi-Quellcode:
procedure TClientDataSetCsvClassHelper.LoadFromFile;
var
myString :Variant;
slFile :TStringList;
slRow :TStringList;
x,i,j :Integer;
myPos :Integer;
myFields :Integer;
cntFields :Integer;
begin
slFile := TStringList.Create;
slRow := TStringList.Create;
try
myPos := 0;
slRow.Delimiter := Delimiter;
slRow.QuoteChar := QuoteChar;
slRow.StrictDelimiter := True;
slFile.StrictDelimiter := True;
slFile.LoadFromFile( Filename );
// ClientDataset Initialisieren
if slFile.Count > 0 then
begin
Active := False;
for x := 0 to slFile.Count - 1 do
begin
myString := '';
if (x = 0) then
begin
myPos := x;
// Build Header for DS
slRow.DelimitedText := slFile[0];
if FirstLineTitle then myFields := slRow.Count else
begin
if (length( slFile[0] )-
length( stringreplace( slFile[0], QuoteChar,'',[rfreplaceall, rfIgnoreCase])) mod 2 = 0) then
myFields := length( slFile[0] )-
length( stringreplace( slFile[0], Delimiter,'',[rfreplaceall, rfIgnoreCase]))
else myFields := slRow.Count;
FieldDefs.Clear;
for i := 0 to myFields - 1 do
begin
FieldDefs.Add( Format( 'Field%d',[i]), ftWideString, StringLength );
end;
end;
if FirstLineTitle then
begin
for i := 0 to myFields - 1 do
FieldDefs.Add( slRow[i], ftWideString, StringLength );
end;
CreateDataSet;
Active := True;
myString := slFile[myPos];
end;
begin
if (x=0) and FirstLineTitle then inc( myPos );
if myPos = slFile.Count then break;
myString := slFile[myPos];
cntFields := length( myString )-
length( stringreplace( myString, Delimiter,'',[rfreplaceall, rfIgnoreCase]));
while cntFields <= (myFields-1) do
if FirstLineTitle and (cntFields < (myFields-1)) then
begin
inc( myPos );
myString := myString+slFile[myPos];
cntFields := length( myString )-
length( stringreplace( myString, Delimiter,'',[rfreplaceall, rfIgnoreCase]));
end
else
if not FirstLineTitle and (x <> 0) then
begin
inc( myPos );
myString := slFile[myPos];
if (length( myString )-
length( stringreplace( myString, QuoteChar,'',[rfreplaceall, rfIgnoreCase])) mod 2 <> 0) then
begin
myString := slFile[myPos-1]+myString;
cntFields := length( myString )-
length( stringreplace( myString, Delimiter,'',[rfreplaceall, rfIgnoreCase]));
end
else
cntFields := length( myString )-
length( stringreplace( myString, Delimiter,'',[rfreplaceall, rfIgnoreCase]));
end
else break;
end;
// fill TClientDataset
DisableControls;
begin
slRow.DelimitedText := myString;
Append;
for j := 0 to slRow.Count - 1 do
begin
Fields[j].AsString := slRow[j];
end;
Post;
end;
EnableControls;
inc( myPos );
end;
end;
finally
slFile.Free;
slRow.Free;
end;
end;
Geändert von Blackpit (21. Mai 2019 um 22:30 Uhr)
|
|
Zitat
|