2022-09-05 08:27:19
<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>
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
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();
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table 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(","));
}
downloadCSV(csv.join("\n"), filename);
}
</script>
<body>
<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 onclick="exportTableToCSV('person.csv')"> Export HTML table to CSV File </button>
</body>
</html>
文章来源:https://www.javatpoint.com/javascript-create-and-download-csv-file
最后生成于 2023-06-27 21:38:25
热门推荐: