javascript 中的换行符为 excel 导入生成了 csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25301960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:19:58  来源:igfitidea点击:

line breaks in javascript generated csv for excel import

javascriptexcelcsvexport-to-excelexport-to-csv

提问by Magnus Siverbrant

I generate and download a CSV from a webpage using javascript in the browser side (chrome windows)

我在浏览器端(chrome windows)使用javascript从网页生成和下载CSV

function toCsv(arr){
    return arr.reduce(function(csvString, row){
        csvString += row.join(',') ;
    csvString += "\r\n";  //";";//"\n";
        return csvString;
    }, '');
}

function flowDataCsv(){
    document.location = 'data:Application/octet-stream,' + toCsv(flowDataGrid);
}

i have tried delimiting lines with ";", "\r\n" and "\n" but all three results in csv:s that excel imports into one line instead of as a grid. How should i terminate the lines to get excel to recognize it as a line ending and start inserting data on a new line?

我试过用“;”、“\r\n”和“\n”分隔行,但所有三个结果都在csv:s中,excel导入到一行而不是作为网格。我应该如何终止行以使 excel 将其识别为行结尾并开始在新行上插入数据?

回答by Lauren3110

Not sure if you still need the answer to this question. But will post the solution I found as I experienced the same problem.

不确定您是否仍然需要这个问题的答案。但是会发布我发现的解决方案,因为我遇到了同样的问题。

Using your code above the only thing you are missing is to encode your csv string returned by your toCsv function. This would look like this in your code above:

使用上面的代码,您唯一缺少的是对您的 toCsv 函数返回的 csv 字符串进行编码。在上面的代码中,这看起来像这样:

function toCsv(arr){
    return arr.reduce(function(csvString, row){
        csvString += row.join(',') ;
    csvString += "\r\n";  //";";//"\n";
        return encodeURIComponent(csvString);
    }, '');
}

function flowDataCsv(){
    document.location = 'data:Application/octet-stream,' + toCsv(flowDataGrid);
}

Hopefully this helps anyone who comes across this issue again in the future!

希望这可以帮助将来再次遇到此问题的任何人!

回答by Delphin Rukundo

Try \u2028instead of \nor \u2029in place of \r.

尝试\u2028代替\n\u2029代替\r

src: https://github.com/zemirco/json2csv/issues/91#issuecomment-276555551

源代码:https: //github.com/zemirco/json2csv/issues/91#issuecomment-276555551