Anyone know how I can import/export csv, txt files in a way similar to NET FileHelpers, but using Delphi, taking spaces and quotes into account and handling traditional CSV esca
My functions
function ParseCSVString(s: string; const delimiter: Char = ','; const enclosure: Char = '"'): TStrings;
var
i,len: Integer;
f: string;
inQuoted: Boolean;
begin
Result := TStringList.Create;
len := Length(s);
if len = 0 then Exit;
//Test,Test;"Test;Test";"Test""Test";;
f := '';
inQuoted := False;
i:=0;
while i < len do
begin
Inc(i);
if s[i] = enclosure then
begin
if inQuoted and (i<len) and (s[i+1] = enclosure) then
begin
f := f + '"';
i:=i+1;
end
else
inQuoted := not inQuoted;
end
else if s[i] = delimiter then
begin
if inQuoted then
f := f+s[i]
else
begin
Result.Add(f);
inQuoted := false;
f := '';
end;
end
else
f := f + s[i];
end;
Result.Add(f);
end;
function EscapeCSVString(s: string; const delimiter: Char = ','; const enclosure: Char = '"'): string;
var
i: Integer;
begin
Result := StringReplace(s,enclosure,enclosure+enclosure,[rfReplaceAll]);
if (Pos(delimiter,s) > 0) OR (Pos(enclosure,s) > 0) then
Result := enclosure+Result+enclosure;
end;