Created
April 1, 2019 15:48
-
-
Save wbatty/3cfcf89494d087efeec5ce470fd9573c to your computer and use it in GitHub Desktop.
Simple example of converting a HTML table to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
</head> | |
<body> | |
<button class="download-csv" data-download-target="results" data-filename="results.csv"></button> | |
<table id="results"> | |
<thead> | |
<tr> | |
<th>Header</th> | |
<!-- ... --> | |
</tr> | |
</thead> | |
<tbody> | |
<tr> | |
<td>Body</td> | |
<!-- ... --> | |
</tr> | |
</tbody> | |
</table> | |
<script type="text/javascript"> | |
document.addEventListener('click', function (event) { | |
if(event.target.matches('.download-csv')){ | |
event.preventDefault; | |
let {filename, downloadTarget} = e.target.dataset; | |
let table = document.getElementById(downloadTarget); | |
filename = filename.matches(/\.csv$/) ? filename : `${filename}.csv`; | |
let csvContent = [...table.querySelectorAll('tr')].map(function(row){ | |
return [...row.querySelectorAll('td,th')].map(function(cell){ | |
return cell.textContent.match(/\W/g) ? `"${cell.textContent}"` : cell.textContent | |
}).join(',') | |
}).join('\n') | |
let link = document.createElement("a"); | |
link.setAttribute('href', `data:text/csv;base64,${btoa(csvContent)}`); | |
link.setAttribute('download', filename); | |
link.style.display = 'none'; | |
link.addEventListener('click', function(event){ | |
event.target.parentElement.removeChild(event.target); | |
}) | |
document.body.appendChild(link); | |
link.dispatchEvent(new MouseEvent('click')); | |
} | |
}, false); | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment