Exporting CSV from NetSuite Suitelet page with Client Scripts

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
define(['N/currentRecord'],
    /**
     * @param{currentRecord} currentRecord
     */
    function (currentRecord) {

        const SUBLIST_ID = 'custpage_report';

        /**
         * Generates and downloads a CSV file containing data from a custom sublist (`custpage_report`)
         * in the current NetSuite record. The CSV file name includes a timestamp for uniqueness.
         *
         * The function iterates over all sublist lines, extracts the field values based on predefined
         * field mappings, escapes any quotes, and compiles the data into a CSV-formatted string.
         * The resulting file is automatically downloaded to the user's system.
         *
         * @throws {Error} Displays an alert if an error occurs during CSV generation or download.
         */
        function downloadCSV() {
            try {
                let record = currentRecord.get();
                let lineCount = record.getLineCount({ sublistId: SUBLIST_ID });
                let fields = [
                    { id: 'item', label: 'Item Name' },
                    { id: 'desc', label: 'Description' },
                    { id: 'location', label: 'Inventory Location' },
                    { id: 'past12_qty_sold', label: 'Past 12 Months Qty Sold' },
                    { id: 'avg_sold_per_month', label: 'Avg. Sold Per Month' },
                    { id: 'revenue_value', label: 'Revenue value' },
                    { id: 'gross_margin', label: 'Gross Margin' },
                    { id: 'margin_percent', label: 'Margin %' },
                    { id: 'min', label: 'Min' },
                    { id: 'max', label: 'Max' },
                    { id: 'on_hand', label: 'On Hand' },
                    { id: 'on_order', label: 'On Order' },
                    { id: 'committed', label: 'Committed' },
                    { id: 'in_transit', label: 'In Transit' },
                    { id: 'available', label: 'Available' },
                    { id: 'back_ordered', label: 'Back Ordered' },
                    { id: 'total_value', label: 'Total Value' },
                    { id: 'recommended_min', label: 'Recommended Min' },
                    { id: 'recommended_max', label: 'Recommended Max' },
                    { id: 'bin_number', label: 'Bin Number' }
                ];
                let csvContent = fields.map(f => `"${f.label}"`).join(',') + 'n';
                for (let i = 0; i < lineCount; i++) {
                    let row = [];
                    fields.forEach(field => {
                        let fieldId = 'custpage_' + field.id;
                        let value = record.getSublistValue({
                            sublistId: SUBLIST_ID,
                            fieldId: fieldId,
                            line: i
                        });
                        value = value !== null && value !== undefined ? value : '';
                        value = String(value).replace(/"/g, '""');
                        row.push(`"${value}"`);
                    });
                    csvContent += row.join(',') + 'n';
                }
                let blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                let link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                let now = new Date();
                let timestamp = now.toISOString().replace(/[:.-]/g, '').slice(0, 15);
                link.download = `Detailed_Inventory_Report_${timestamp}.csv`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } catch (error) {
                console.error("Error @ downloadCSV", error);
                alert('Error downloading CSV: ' + error.message);
                return;
            }
        }

        return {
            downloadCSV: downloadCSV
        };

    });

Leave a comment

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