Skip to content

Instantly share code, notes, and snippets.

@petermann
Created September 18, 2025 20:34
Show Gist options
  • Select an option

  • Save petermann/d3c62976c3c53bad062cb1e153a73758 to your computer and use it in GitHub Desktop.

Select an option

Save petermann/d3c62976c3c53bad062cb1e153a73758 to your computer and use it in GitHub Desktop.
Adds export buttons (Excel, CSV, JSON) to a DataTables table, normalizing numeric fields like price and product dimensions for JSON export.
<script>
document.addEventListener('DOMContentLoaded', function() {
var table = new DataTable('#example', {
scrollX: true,
searching: false,
scrollY: "600px",
scrollCollapse: true,
paging: false,
fixedColumns: {
leftColumns: 1
},
order: [
[2, 'asc']
],
dom: 'Bfrtip', // enable export buttons
buttons: [
{
extend: 'excelHtml5',
text: 'Export Excel',
title: 'weelko_products'
},
{
extend: 'csvHtml5',
text: 'Export CSV',
title: 'weelko_products'
},
{
text: 'Export JSON',
action: function (e, dt, node, config) {
// get column headers
var headers = dt.columns().header().toArray().map(h => $(h).text().trim());
// map rows to objects using headers as keys
var data = dt.rows({ search: 'applied' }).data().toArray().map(row => {
var obj = {};
headers.forEach((h, i) => {
let value = row[i];
// normalize numeric fields (prices, weight, volume, dimensions)
if (
h.toLowerCase().includes("price") ||
h.toLowerCase().includes("weight") ||
h.toLowerCase().includes("volume") ||
h.toLowerCase().includes("height") ||
h.toLowerCase().includes("length") ||
h.toLowerCase().includes("width")
) {
if (typeof value === "string") {
value = value
.replace(/[^\d,.-]/g, "") // remove symbols like € or spaces
.replace(",", "."); // replace comma with dot
value = parseFloat(value) || 0;
}
}
obj[h] = value;
});
return obj;
});
// convert to formatted JSON
var json = JSON.stringify(data, null, 2);
// create a blob and force download
var blob = new Blob([json], { type: "application/json" });
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "weelko_products.json";
a.click();
URL.revokeObjectURL(url);
}
}
]
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment