HLJ 发布于
2022-09-05 08:27:19

JavaScript代码将table表格数据导出到csv文件

<html>  
<head>  
<title> Export HTML table Data to CSV using JavaScript </title>  
  
<style>  
*{  
     color:#2b2b2b;  
     font-family: "Roboto Condensed";  
}  
table {   
     width:40%;  
}  
th {  
     text-align:left;  
     color:#4679bd;  
}  
</style>  
</head>  
  
<script>  
//user-defined function to download CSV file  
function downloadCSV(csv, filename) {  
    var csvFile;  
    var downloadLink;  
     
    //define the file type to text/csv  
    csvFile = new Blob([csv], {type: 'text/csv'});  
    downloadLink = document.createElement("a");  
    downloadLink.download = filename;  
    downloadLink.href = window.URL.createObjectURL(csvFile);  
    downloadLink.style.display = "none";  
  
    document.body.appendChild(downloadLink);  
    downloadLink.click();  
}  
  
//user-defined function to export the data to CSV file format  
function exportTableToCSV(filename) {  
   //declare a JavaScript variable of array type  
   var csv = [];  
   var rows = document.querySelectorAll("table tr");  
   
   //merge the whole data in tabular form   
   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(","));  
   }   
   //call the function to download the CSV file  
   downloadCSV(csv.join("\n"), filename);  
}  
</script>  
  
<body>  
<!-- create table and provide data inside it -->  
<table>  
<tr>  
    <th> Name </th>  
    <th> Profession </th>  
    <th> Age </th>  
    <th> Hobby </th>  
</tr>  
<tr>  
    <td> Cristiano </td>  
    <td> Hacker </td>  
    <td> 24 </td>  
    <td> Travelling, Sky-diving </td>  
</tr>  
<tr>  
    <td> Jenifer </td>  
    <td> Photographer </td>  
    <td> 22 </td>  
    <td> Cooking </td>  
</tr>  
<tr>  
    <td> Simon </td>  
    <td> Travelling-guide </td>  
    <td> 35 </td>  
    <td> Dancing, Gardening </td>  
</tr>  
<tr>  
    <td> Cristiano Ronaldo </td>  
    <td> Footballer </td>  
    <td> 29 </td>  
    <td> Singing </td>  
</tr>  
</table>  
<p><b> Click the Download CSV button to download the created data </b></p>  
  
<!-- button to call the user-defined function to download CSV file data -->  
<button onclick="exportTableToCSV('person.csv')"> Export HTML table to CSV File </button>   
</body>  
</html>  
文章来源:https://www.javatpoint.com/javascript-create-and-download-csv-file
最后生成于 2022-10-07 22:28:03