beetlejoose
Programmer
The following procedure parses a record from a .csv file and passes back the fields read in the Strings parameter.
This works with .csv files exported from Excel etc. Null fields, fields containing comma's and double quotes etc are all parsed correctly.
procedure ReadCSVRecord(var CSVFile : TextFile; Strings : TStrings);
var P : PChar;
Line, Field : string;
Quote : boolean;
begin
ReadLn(CSVFile, Line);
Strings.Clear;
if length(Line) > 0 then
begin
P := @Line[1];
repeat
Field := '';
if P^ = '"' then
begin
Inc(P);
repeat
while P^ <> '"' do
begin
Field := Field + P^;
Inc(P);
end;
Quote := False;
while P^ = '"' do
begin
Inc(P);
if Quote then Field := Field + '"';
Quote := not Quote;
end;
until (P^ = #0) or Quote;
end
else
begin
while (P^ <> #0) and (P^ <> ',') do
begin
Field := Field + P^;
Inc(P);
end;
end;
Strings.Add(Field);
if P^ = #0 then exit;
Inc(P);
until P^ = #0;
Strings.Add('');
end;
end;
This works with .csv files exported from Excel etc. Null fields, fields containing comma's and double quotes etc are all parsed correctly.
procedure ReadCSVRecord(var CSVFile : TextFile; Strings : TStrings);
var P : PChar;
Line, Field : string;
Quote : boolean;
begin
ReadLn(CSVFile, Line);
Strings.Clear;
if length(Line) > 0 then
begin
P := @Line[1];
repeat
Field := '';
if P^ = '"' then
begin
Inc(P);
repeat
while P^ <> '"' do
begin
Field := Field + P^;
Inc(P);
end;
Quote := False;
while P^ = '"' do
begin
Inc(P);
if Quote then Field := Field + '"';
Quote := not Quote;
end;
until (P^ = #0) or Quote;
end
else
begin
while (P^ <> #0) and (P^ <> ',') do
begin
Field := Field + P^;
Inc(P);
end;
end;
Strings.Add(Field);
if P^ = #0 then exit;
Inc(P);
until P^ = #0;
Strings.Add('');
end;
end;