【问题标题】:\r\n characters in CSV file not treated as line breaks\r\n CSV 文件中的字符不被视为换行符
【发布时间】:2016-12-17 17:32:11
【问题描述】:

抱歉,这肯定是一个愚蠢的问题...... 我正在尝试创建一个如下所示的 CSV 文件:

Header1,Header2,Header3, "Value1","Value2","Value3"

相反,我得到的 CSV 文件如下所示: Header1,Header2,Header3,\r\n"Value1","Value2","Value3"

如何让我的 CRLF 字符在输出中实际产生换行符?

我正在做的是对从存储过程生成数据表的 WebMethod 进行 ajax 调用。然后将该数据表解析为 CSV,如下所示:

if (!createHeaders)//I deal with the headers elsewhere in the code
{
    foreach(DataColumn col in table.Columns){

        result += col.ColumnName + ",";
    };
    result += Environment.NewLine;
}

for (int rowNum = 0; rowNum < table.Rows.Count; rowNum++) 
{
    for (int colNum = 0; colNum < table.Columns.Count; colNum++)
    {
        result += "\"" + (table.Rows[rowNum][colNum]).ToString();
        result += "\",";
    };
    result += Environment.NewLine;
};
return result;
}

然后将该字符串传递回 ajax 查询的成功函数,在那里它会经历更多的转换...

function getExportFile(sType) {
    var alertType = null
    $.ajax({
        type: "POST",      
        url: "./Services/DataLookups.asmx/getExcelExport",
        data: JSON.stringify({ sType: sType }),
        processData: false,
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        success: function (response) {                
            response = replaceAll(response,"\\\"", "\"")
            response = response.replace("{\"d\":\"", "")
            response = response.replace("\"}", "")
            download(sType + ".csv",response)
        }
    });

    function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click()
        document.body.removeChild(element);
    }

    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

在字符串传回 javascript 之前的调试中,如果我只键入 ?response,我会得到不正确的全在线响应。但是,当我键入 ?resonse,nq 时,会识别换行符,并且一切看起来都应该如此。

另外,我敢肯定我在这里做错/愚蠢的事情有很多。也感谢指出这些实例。

【问题讨论】:

  • 你在调试器或输出文件中看到\r\n 吗?
  • 两者。当我请求“?response,nq”时,它们会在调试器中消失,但在我请求“?response”时会出现

标签: javascript c# .net export-to-csv line-breaks


【解决方案1】:

您的标头应该具有data:Application/octet-stream, 作为 MIME 类型而不是 data:text/plain;charset=utf-8,,原因是根据 HTTP 规范,当内容类型未知时,接收者应将其视为类型 application/octet-stream。

由于您已经在使用encodeURIComponent(),这似乎是唯一剩下的问题。

【讨论】:

    【解决方案2】:

    @AryKay 的回答肯定有帮助,但还有一个问题。 Ajax 调用返回的字符串将\r\ns 转义为文字。跑了一个

    Response = response.replace (/\\r\\n/g, "\r\n")

    在传递给encodeURIComponent 之前,它就像一个魅力一样运行。

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2016-08-27
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多