2017-09-24 29 views
0

我有这个代码,它允许我使用二维数组下载CSV文件,但是我需要在第一个数组中的最后一项后面有一个换行符。 (刚过some other info在JavaScript中的数组中的最后一项后行换行

<script type="text/javascript"> 

    // Example data given in question text 
    var data = [ 
     ['name1', 'city1', 'some other info'], 
     ['name2', 'city2', 'more info'] 
    ]; 

    // Building the CSV from the Data two-dimensional array 
    // Each column is separated by ";" and new line "\n" for next row 
    var csvContent = ''; 
    data.forEach(function(infoArray, index) { 
     dataString = infoArray.join(';'); 
     csvContent += index < data.length ? dataString + '\n' : dataString; 
    }); 

    // The download function takes a CSV string, the filename and mimeType as parameters 
    // Scroll/look down at the bottom of this snippet to see how download is called 
    var download = function(content, fileName, mimeType) { 
     var a = document.createElement('a'); 
     mimeType = mimeType || 'application/octet-stream'; 

     if (navigator.msSaveBlob) { // IE10 
      navigator.msSaveBlob(new Blob([content], { 
       type: mimeType 
      }), fileName); 
     } else if (URL && 'download' in a) { //html5 A[download] 
      a.href = URL.createObjectURL(new Blob([content], { 
       type: mimeType 
      })); 
      a.setAttribute('download', fileName); 
      document.body.appendChild(a); 
      a.click(); 
      document.body.removeChild(a); 
     } else { 
      location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported 
     } 
    } 

    download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8'); 
</script> 

所以要明确的,那我现在得到的结果是:

name1;city1;some other infoname2;city2;more info 

,我需要它是:

name1;city1;some other info 
name2;city2;more info 

由于一吨

回答

1

可能是因为无论您用什么来显示文件,都希望Windows行结束而不是UNI X行结尾。尝试使用\r\n而不仅仅是\n

+0

就是这样,谢谢! – dwix

+1

此外,如果您将内容显示为网页的一部分,则\ n将转换为空格。在这种情况下,你需要'
'。 –

+0

我明白,谢谢。 – dwix

相关问题