【发布时间】: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