For many reasons, you may occasionally want to export the data out from the custom reports into a tabular or spreadsheet format for manipulation.
Custom reports are built using HTML and XSL tokens. You can render the data separately into a Javascript string that is hidden from the normal view. Simply include a button to retrieve the data to CSV and send to the window object using Javascript. For example, the following Javascript code can be used to trigger the download of the CSV file.
<script>
function downloadFile(fileName, data) {
var a = document.createElement("a");
if (navigator.msSaveBlob) {
navigator.msSaveBlob(new Blob([data], {
type: "text/csv"
}), fileName);
} else if ('download' in a) {
a.href = 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data);
a.download = fileName;
document.body.appendChild(a);
setTimeout(function() {
a.click();
document.body.removeChild(a);
}, 100);
} else if (document.execCommand) {
var oWin = window.open("about:blank", "_blank");
oWin.document.write(data);
oWin.document.close();
oWin.document.execCommand('SaveAs', true, fileName);
oWin.close();
}
}
function exportCsv() {
var data = '"Order","Status"\r\n';
{xsl:for-each select="/in/dataSet/dataTable/dataRow" }
data += '"{xsl:value-of select="SalesOrderNumber" /}","{xsl:value-of select="Status" /}"\r\n';
{/xsl:for-each}
downloadFile('Orders.csv', data);
}
</script>
<p><button class="btn btn-link" type="button" onclick="exportCsv()" style="float: right">Export</button></p>
You can find many examples online on how to use Javascript to export CSV. Some examples are shown here: