How can I read and write CSV in a way similar to NET FileHelpers?

后端 未结 7 630
感动是毒
感动是毒 2021-02-03 12:11

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

相关标签:
7条回答
  • 2021-02-03 12:46

    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;
    
    0 讨论(0)
提交回复
热议问题