2017-08-11 63 views
0

我試圖使用Javascript下載CSV報告。但是,我在CSV中遇到了一些編碼問題。我得到&&以下是我的JS代碼。我嘗試了谷歌的解決方案,但無濟於事。使用&符號的CSV角度2編碼問題

JSONToCSVConvertor(ReportTitle, ShowLabel) { 
    let csv = []; 

    var tableId = document.querySelector('table').getAttribute('id'); 

    var headers = document.querySelectorAll("table#"+tableId+" tr"); 

    for (var i = 0; i < headers.length; i++) { 

    var row = [], cols = headers[i].querySelectorAll("td, th"); 

    for (var j = 0; j < cols.length; j++) 

     row.push(cols[j].innerHTML); 


    csv.push(row.join(", ")); 

} 

this.downloadCSV(csv.join("\n"), sampleTitle); 

downloadCSV(csv, filename) { 
    var csvFile; 
    var downloadLink; 

    var uri = 'data:text/csv;charset=utf-8' + encodeURI(csv); 

// Download link 
    downloadLink = document.createElement("a"); 


    downloadLink.href = uri; 

    downloadLink.download = filename + ".csv"; 

    // Hide download link 
    downloadLink.style.display = "none"; 

    // Add the link to DOM 
    document.body.appendChild(downloadLink); 

    // Click download link 
    downloadLink.click(); 

    document.body.removeChild(downloadLink); 
} 

如何獲取CSV中的確切特殊字符?任何幫助?

+0

'encodeURI'不會改變'&'...你想'encodeURIComponent'也許 –

回答

0

不知道這是矯枉過正...

function encodeRFC5987ValueChars(str) { 
    return window.encodeURIComponent(str) 
     .replace(/['()]/g, window.escape) 
     .replace(/\*/g, '%2A') 
     .replace(/%(?:7C|60|5E)/g, window.unescape); 
}