Hi guys,
here is an easy way to let visitors export data to excel (csv file), include Hebrew.
What you need is:
1) Create dataset for the collection you want to export
2) iFrame element
Button click code:
export async function button1_click(event) {
await $w("#dataset1").onReady( () => { } );
let totalcount = $w("#dataset1").getTotalCount()-1; //find matrix number of rows
let itemObj = $w("#dataset1").getCurrentItem();
let colNum = Object.keys(itemObj).length; //find matrix number of column
var matrix = []; //define the matrix
for(var k=0; k<totalcount; k++) {
matrix[k] = new Array(colNum).fill(0);
}
let result =await $w("#dataset1").getItems(0,totalcount);
let items = result.items;
for (var j = 0; j < totalcount; j++) {
let arr = Object.values(items[j]);
for (var i = 0; i < arr.length; i++) {
matrix[j][i]=arr[i];
}
}
$w('#html1').postMessage(matrix);
}
iFrame code (just copy-paste)
<html>
<head>
<script type="text/javascript">
var Results = [];
window.onmessage = function(event){
if (event.data) {
let receivedData = event.data;
Results =receivedData;
}
else {
console.log("if error");
}
};
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
CsvString = "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURIComponent(CsvString);
var x = document.createElement("A");
x.setAttribute("href", CsvString );
x.setAttribute("download","somedata.csv");
document.body.appendChild(x);
x.click();
}
</script>
</head>
<body>
<button onclick="exportToCsv()">export to CSV</button>
</body>
</html>
Let me know if you have any questions :)
Thank you for your contribution.
Being moved to Tips, Tutorials, Examples