CSV文件中的\ r \ n个字符不被视为换行符 [英] \r\n characters in CSV file not treated as line breaks

查看:340
本文介绍了CSV文件中的\ r \ n个字符不被视为换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,这无疑是一个头绪问题... 我正在尝试创建一个如下所示的CSV文件:

Apologies for what is surely a bonehead question... I am trying to create a CSV file that looks like this:

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

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

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

Instead, I'm getting a CSV file that looks like this: Header1,Header2,Header3,\r\n"Value1","Value2","Value3"

如何获取CRLF字符以在输出中实际产生换行符?

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

What I'm doing is making an ajax call to a WebMethod that generates a datatable from a stored proc. That datatable is then parsed out to a CSV like so:

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查询的成功函数,在该函数中进行一些其他转换...

That string is then passed back to the success function of the ajax query, where it undergoes a few more transformations...

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时,可以识别换行符,并且一切看起来都应该如此.

In my debugging before the string is passed back to javascript, if I just type ?response, I get the incorrect, all-on-one-line response. However, when I type ?resonse,nq the linebreaks are recognized, and everything looks the way it should.

此外,我确定这里有很多我做错/愚蠢的事情.指出这些实例也很感激.

Also, I'm sure there is PLENTY that I'm doing wrong/stupidly here. Pointing out those instances is also appreciated.

推荐答案

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

Your header should have data:Application/octet-stream, as MIME-type instead of data:text/plain;charset=utf-8,, the reason being that as per HTTP specifications, when the content type is unknown, the recipient should treat it as type application/octet-stream.

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

Since you are already using the encodeURIComponent(), that seems to be the only issue remaining.

这篇关于CSV文件中的\ r \ n个字符不被视为换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆