2017-09-22 33 views
1

我轉換HTML表數據Excel的CSV文件和我使用下面的代碼爲了保存HTML表數據在Excel文件

<script> 

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

     // CSV file 
     csvFile = new Blob([csv], {type: "text/csv"}); 

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

     // File name 
     downloadLink.download = filename; 

     // Create a link to the file 
     downloadLink.href = window.URL.createObjectURL(csvFile); 

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

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

     // Click download link 
     downloadLink.click(); 
    } 



    function exportTableToCSV(filename) { 
     var csv = []; 
     var rows = document.querySelectorAll("#faqs tr"); 
     for (var i = 0; i < rows.length; i++) { 

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

      for (var j = 0; j < cols.length; j++) 
       row.push(cols[j].innerText); 

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

     // Download CSV file 
     downloadCSV(csv.join("\n"), filename); 
    } 

</script> 

問題是,當這個腳本生成excel工作表是不以適當的格式。

從圖片你可以看到問題列的文本中包含逗號,,所以逗號造成問題。所有的excel字段都不是我想要的格式。我想列出與各列相關的所有數據,但問題列令人困惑。

按鈕:

<button onclick="exportTableToCSV('faqs.csv')"> Export CSV</button> 

感謝

Data in excel

+0

你需要引用包含逗號的列。 https://superuser.com/questions/309122/importing-csv-into-excel-with-commas-in-quoted-fields –

+0

@AlanLarimer如何通過Javascript來做到這一點?因爲我將HTML表格轉換爲CSV。謝謝 –

+0

這有幫助嗎? [我怎樣才能導出表從excel從網頁](https://stackoverflow.com/questions/5524143/how-can-i-export-tables-to-excel-from-a-webpage) – Granny

回答

0
for (columnCounter = 0; columnCounter < totalColumns; columnCounter++) { 
    // quote each column in order to escape any commas 
    row.push('"' + cols[columnCounter].innerText + '"'); 
    } 

https://jsbin.com/zepabey/edit?html,console,output

+0

謝謝引用完美:) –