Suitelet to display Search results and Download as CSV

Solution

Suitelet Code

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
define(["N/ui/serverWidget", "N/search"], function (serverWidget, search) {
    function onRequest(context) {
        if (context.request.method === "GET") {
            var form = serverWidget.createForm({
                title: "Search Results Suitelet"
            });

            // ... (rest of the code)

            // Add a download button to the form
            form.addButton({
                id: "custpage_download_button",
                label: "Download CSV",
                functionName: "downloadCSV()"
            });

            // ... (rest of the code)

            context.response.writePage(form);
        }
    }

    function generateCSV(searchResults) {
        var csvContent = "Entity ID,Company Name\n"; // CSV header

        searchResults.forEach(function (result) {
            var entityId = result.getValue("entityid");
            var companyName = result.getValue("companyname");
            csvContent += entityId + "," + companyName + "\n";
        });

        return csvContent;
    }

    return {
        onRequest: onRequest
    };
});

Download CSV

function downloadCSV() {
    var searchResults = /* Get your search results here */;
    var csvContent = generateCSV(searchResults);

    var blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    var link = document.createElement("a");
    if (link.download !== undefined) {
        var url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", "search_results.csv");
        link.style.visibility = "hidden";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *