最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

line breaks in javascript generated csv for excel import - Stack Overflow

programmeradmin2浏览0评论

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

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?

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

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?

Share Improve this question asked Aug 14, 2014 at 7:02 Magnus SiverbrantMagnus Siverbrant 1331 gold badge1 silver badge7 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

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:

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!

Try \u2028 instead of \n or \u2029 in place of \r.

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

发布评论

评论列表(0)

  1. 暂无评论