2017-09-24 9 views
0

2次元配列を使用してCSVファイルをダウンロードできるこのコードがありますが、最初の配列の最後の項目の直後に改行が必要です。 。Javascriptの配列の最後の項目の後の改行

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

と私はそれがする必要があります:(直後some other info

<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 info 
name2;city2;more info 

おかげトンで

答えて

1

ファイルを表示するために使用しているものは、UNIの代わりにWindowsの行末が必要な場合がありますX行の終わり。ちょうど\nの代わりに\r\nを試してください。

+0

これは、ありがとうございました! – dwix

+1

また、Webページの一部としてコンテンツを表示していた場合、 '\ n'は空白に変換されます。その場合は '
'が必要です。 –

+0

私は、ありがとう、理解する。 – dwix

関連する問題