To directly export an Excel file to the user’s system upon clicking a button on the suitelet page, we can use the following method.
Client script function:
function exportExcel() {
try {
const filename = 'fileName';
// Build up the XML string and set encoding for Excel
xmlString = ``; //added the xmlString of the Excel file that is to be exported
const uri = 'data:text/xls;charset=utf-8,ufeff' + encodeURIComponent(xmlString);
// Create a temporary link element to trigger the download
const downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = filename + ".xls";
// Append the link to the document, trigger download, and remove the link
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
} catch (error) {
console.error('Error exporting Excel: ', error);
}
}
Suitelet script:
/**
* @NApiVersion 2.x
* @NScriptType Suitelet
*/
define(['N/ui/serverWidget'], function(serverWidget) {
function onRequest(context) {
if (context.request.method === 'GET') {
var form = serverWidget.createForm({title: 'Export Excel Example'});
// Add a button to trigger the client-side function
form.addButton({
id: 'custpage_export_excel',
label: 'Export to Excel',
functionName: 'exportExcel()'
});
// Write out the client script to be included in the Suitelet form
form.clientScriptModulePath = './export_excel_client_script.js'; // path to client script
context.response.writePage(form);
}
}
return {
onRequest: onRequest
};
});