JavaScript - HTML-Tabelle als CSV-Datei exportieren
Diese Tabelle als CSV-Datei exportieren (herunterladen).
Nr. | Vorname | Name | Alter |
---|---|---|---|
1 | Andrea | Ross | 18 |
2 | Penelope | Mills | 36 |
3 | Sarah | Grant | 14 |
4 | Vanessa | Roberts | 27 |
5 | Oliver | Alsop | 12 |
6 | Jennifer | Forsyth | 7 |
7 | Michelle | King | 21 |
8 | Steven | Kelly | 55 |
9 | Julian | Ferguson | 15 |
10 | Chloe | Ince | 23 |
11 | Sarah | Myer | 22 |
Siehe auch: HTML-Tabelle filtern, HTML-Tabelle sortieren, HTML-Tabelle Spaltenbreite anpassen, Tabellenkalender und CSV-Datei einlesen und dynamisch als Tabelle ausgeben
<style>
table#foobar-table thead {
position: sticky;
}
table#foobar-table thead {
inset-block-start: 0;
}
table#foobar-table,
table#foobar-table > thead > tr > th,
table#foobar-table > tbody > tr > td {
border: Solid 1px #888888;
padding: 5px;
}
table#foobar-table > thead > tr {
background-color: #FFAE5E;
}
table#foobar-table > tbody > tr:nth-child(even) {
background-color: #FFFFFF;
}
table#foobar-table > tbody > tr:nth-child(odd) {
background-color: #FFD2A6;
}
#foobar-table {
margin-left: 50px;
}
.resizer {
position: Absolute;
top: 0;
right: 0;
width: 5px;
cursor: w-resize;
user-select: None;
}
</style>
<table id="foobar-table">
<thead>
<tr>
<th>Nr.</th>
<th>Vorname</th>
<th>Name</th>
<th>Alter</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Andrea</td>
<td>Ross</td>
<td>18</td>
</tr>
<tr>
<td>2</td>
<td>Penelope</td>
<td>Mills</td>
<td>36</td>
</tr>
<tr>
<td>3</td>
<td>Sarah</td>
<td>Grant</td>
<td>14</td>
</tr>
</tbody>
</table>
<p><button class=button id="export">Exportieren</button></p>
<script>
// HTML-Tabelle als CSV-Datei exportieren
document.addEventListener('DOMContentLoaded', function() {
const table = document.getElementById('foobar-table');
const exportBtn = document.getElementById('export');
const toCsv = function(table) {
const rows = table.querySelectorAll('tr');
return [].slice.call(rows)
.map(function(row) {
const cells = row.querySelectorAll('th,td');
return [].slice.call(cells)
.map(function(cell) {
return cell.textContent;
})
.join(',');
})
.join('\n');
};
const download = function(text, fileName) {
const link = document.createElement('a');
link.setAttribute('href', `data:text/csv;charset=utf-8,${encodeURIComponent(text)}`);
link.setAttribute('download', fileName);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
exportBtn.addEventListener('click', function() {
const csv = toCsv(table);
download(csv, 'download.csv');
});
});
</script>
Bausteine Alle Anzeigen
Eine zufällige Auswahl von Codeschnipseln
aus den Bereichen
HTML, CSS,
PHP, JavaScript und
MySQL.
<strong> Stark betonter Inhalt
CSS - Internes Sprungziel hervorheben
PHP - Zufällige Texte ausgeben