How should I escape commas and speech marks in CSV files so they work in Excel?

后端 未结 5 1157
说谎
说谎 2020-11-29 00:20

I\'m generating a CSV file (delimited by commas rather than tabs). My users will most likely open the CSV file in Excel by double clicking it. My data may contain commas and

5条回答
  •  温柔的废话
    2020-11-29 00:33

    According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).

    FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
        C_NEWLINE CONSTANT CHAR(1) := '
    '; -- newline is intentional
    
        v_aux VARCHAR2(32000);
        v_has_double_quotes BOOLEAN;
        v_has_comma BOOLEAN;
        v_has_newline BOOLEAN;
    BEGIN
        v_has_double_quotes := instr(str, '"') > 0;
        v_has_comma := instr(str,',') > 0;
        v_has_newline := instr(str, C_NEWLINE) > 0;
    
        IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
            IF v_has_double_quotes THEN
                v_aux := replace(str,'"','""');
            ELSE
                v_aux := str;
            END IF;
            return '"'||v_aux||'"';
        ELSE
            return str;
        END IF;
    END;
    

提交回复
热议问题