代码之家  ›  专栏  ›  技术社区  ›  sword1st

如何转义“,”以写入CSV文件[重复]

  •  0
  • sword1st  · 技术社区  · 7 年前

    我正在生成一个CSV文件(由逗号而不是制表符分隔)。我的用户很可能通过双击在Excel中打开CSV文件。我的数据可能包含逗号和语音标记,因此我将按如下方式进行转义。

    Reference, Title, Description
    1, "My little title", "My description, which may contain ""speech marks"" and commas."
    2, "My other little title", "My other description, which may also contain ""speech marks"" and commas."
    

    据我所知,这一直是做这件事的方法。这是我的困惑:当我在Excel 2010中打开此文件时,我的转义不受尊重。工作表上会出现语音标记,逗号会产生新的列。

    0 回复  |  直到 10 年前
        1
  •  231
  •   centralscru    13 年前

    我们最终找到了答案。

    如果列值前面没有空格,Excel将只考虑逗号和语音标记的转义。因此,生成没有空格的文件时,如下所示。。。

    Reference,Title,Description
    1,"My little title","My description, which may contain ""speech marks"" and commas."
    2,"My other little title","My other description, which may also contain ""speech marks"" and commas."
    

    ... 解决了这个问题。希望这对别人有帮助!

        2
  •  64
  •   Community CDub    11 年前

    以下是规则,如果你认为它是随机的。可以根据这些规则创建效用函数。

    1. 如果值包含逗号、换行符或双引号,则返回的字符串值应包含在双引号中。

    2. 值中的任何双引号字符都应使用另一个双引号转义。

        3
  •  2
  •   aaguilera    10 年前

    根据Yashu的说明,我编写了以下函数(它是PL/SQL代码,但应该很容易适应任何其他语言)。

    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;
    
        4
  •  0
  •   golimar    7 年前

    'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'
    

    Excel将把它放在5列中(如果您在“文本到列”向导中选择单个引号作为“文本限定符”)

        5
  •  -3
  •   Ramkumar Navaneethakrishnan    10 年前

    将管道分隔符替换为逗号,然后一切正常。