ANS-1172 · SUITESCRIPT DEVELOPMENT
How to Generate a CSV File for Download in NetSuite Suitelets Without Storing It?
Learn how to dynamically create and serve a CSV file directly from a NetSuite Suitelet, enabling immediate user download without saving to the File Cabinet.
Short answer
To generate a CSV file for download without storing it in NetSuite's File Cabinet, create a Suitelet that dynamically constructs the CSV content as a string. Then, use `context.response.addHeader()` to set the 'Content-Type' and 'Content-Disposition' headers, followed by `context.response.write()` to output the CSV string, prompting the user to save the file.
Scenario
NetSuite users often require the ability to generate data exports in CSV format directly from a Suitelet. The challenge is to provide this functionality without the intermediate step of saving the generated file to the NetSuite File Cabinet, which can be inefficient for one-time downloads or dynamic reports.
Solution
A CSV file is a text file where values are separated by delimiters, typically commas. To generate a CSV file for direct download from a NetSuite Suitelet without storing it in the File Cabinet, follow these steps:
Define a Suitelet script with an
onRequestentry point.Within the
onRequestfunction, initialize a string variable to hold the CSV content.Dynamically build the CSV string, including headers and data. Each row should be separated by a carriage return and newline (
rn).Set the appropriate HTTP headers using
context.response.addHeader()to specify the content type as 'text/csv' and suggest a filename for download.Finally, write the complete CSV string to the response using
context.response.write().Below is an example Suitelet code snippet demonstrating this approach:
javascript/** * @NApiVersion 2.x * @NScriptType Suitelet */define([], function() { function suiteletEntryPoint(context) { var csv = ''; // Dynamically create the CSV structure // Header csv + 'Id,Name' + 'rn'; csv + '101,Stan'; // Set response headers for CSV download context.response.addHeader({ name: 'Content-Type', value: 'text/csv' }); context.response.addHeader({ name: 'Content-Disposition', value: 'attachment; filename="File Name.csv"' }); // Write the CSV content to the response context.response.write({ output: csv }); } return { onRequest: suiteletEntryPoint };});Expert NetSuite Support
Need help with this NetSuite issue?
SuiteScript Development consulting and configuration support
