2016-08-11 21 views
1

道歉什么肯定是一个笨蛋问题... 我想创建一个CSV文件看起来像这样: r n的CSV字符的文件不被视为断行

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

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

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

我在做什么是ajax调用WebMethod从存储过程生成一个数据表。然后,该数据表中分析出到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,我会得到不正确的全部一行响应。然而,当我输入?反应时,nq可以识别换行符,并且看起来应该是一切。

此外,我敢肯定,我在这里做错了/愚蠢的事情。指出这些实例也值得赞赏。

+1

你在调试器或输出文件中看到'\ r \ n'吗? – user3185569

+0

两者。当我请求“?response,nq”时,它们在调试器中消失,但当我请求“?response”时出现, – nwhaught

回答

1

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

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

0

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

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

传递给encodeURIComponent之前和它跑就像一个魅力。

相关问题