Create a CSV file using the saved search.

/**
 * Suitelet script to export saved search results as CSV.
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */

/**
 * Handles incoming requests to generate and export CSV from saved search.
 * @param {Object} context - The context object
 * @param {ServerRequest} context.request - The request object
 * @param {ServerResponse} context.response - The response object
 */
function onRequest(context) {
    if (context.request.method === 'GET') {
        var savedSearchId = 'YOUR_SAVED_SEARCH_ID'; // Replace with your saved search ID
        var savedSearch = search.load({ id: savedSearchId });

        var batchSize = 1000; // Number of records per batch
        var searchResults = [];
        var startIndex = 0;

        while (true) {
            var batchResults = savedSearch.run().getRange({
                start: startIndex,
                end: startIndex + batchSize
            });

            if (batchResults.length === 0) {
                break; // No more results
            }

            searchResults = searchResults.concat(batchResults);
            startIndex += batchSize;
        }

        var csvContent = '';
        var columnLabels = [];

        // Get column labels
        savedSearch.columns.forEach(function (column) {
            columnLabels.push(column.label);
        });
        csvContent += columnLabels.join(',') + '\n';

        // Process search results and build CSV content
        searchResults.forEach(function (result) {
            var rowData = [];
            savedSearch.columns.forEach(function (column) {
                rowData.push('"' + result.getText(column) + '"');
            });
            csvContent += rowData.join(',') + '\n';
        });

        // Set response headers for CSV download
        context.response.setHeader({
            name: 'Content-Disposition',
            value: 'attachment; filename=saved_search_results.csv'
        });

        // Write CSV content to the response
        context.response.write(csvContent);
    }
}

The following Sutelet script helps to download CSV files from a saved search dynamically. The CSV headings will be the name of each result column.

Note: We can not get the formula field column name using this script.

Leave a comment

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