2017-09-24 32 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

相關問題