procedure csvLesen(Datei: string; grd: TSTringgrid; Kopfzeile: boolean);
var
s: string;
gilt: boolean;
sl: TStringlist;
i, x, y, z, p, b: integer;
begin
if fileexists(Datei) then begin
screen.cursor := crHourglass;
sl := TStringlist.create;
try
sl.loadfromfile(Datei);
if sl.count > 0 then begin
for y := 0 to sl.count - 1 do begin
sl[y] := stringreplace(sl[y], '„', '""', [rfReplaceall]);
sl[y] := stringreplace(sl[y], '“', '""', [rfReplaceall]);
end;
gilt := true;
z := 0;
for x := 1 to length(sl[0]) do begin
if sl[0][x] = '"' then gilt := not gilt;
if gilt and (sl[0][x] = ';') then inc(z);
end;
for y := 0 to sl.count - 1 do begin
gilt := false;
for x := 1 to length(sl[y]) do begin
if sl[y][x] = '"' then gilt := not gilt;
if gilt and (sl[y][x] = ';') then
sl[y] := copy(sl[y], 1, x - 1) + #1 + copy(sl[y], x + 1, maxint);
end;
end;
with grd do begin
colcount := z + 1;
Fixedrows := ord(Kopfzeile);
Fixedcols := 0;
Rowcount := sl.count;
Defaultcolwidth := 5;
Canvas.Font := Font;
for x := 0 to sl.count - 1 do
for y := 0 to z do begin
p := pos(';', sl[x]);
if p > 0 then begin
s := copy(sl[x], 1, p - 1);
sl[x] := copy(sl[x], p + 1, maxint);
end else s := sl[x];
s := stringreplace(s, #1, ';', [rfReplaceall]);
i := 1;
while i <= length(s) do begin
if (s[i] = '"') then delete(s, i, 1);
inc(i);
end;
cells[y, x] := s;
b := canvas.textwidth(s) + 5;
if b > colwidths[y] then colwidths[y] := b;
end;
end;
end;
except
showmessage('Fehler beim Einlesen');
end;
sl.free;
screen.cursor := crDefault;
end else
showmessage('Datei nicht gefunden');
end;
// Beispielaufruf
procedure TForm1.Button3Click(Sender: TObject);
begin
csvLesen('c:\test.csv', StringGrid1, true);
end;