← Script library

UI Actions

Export to CSV (List Action)

Export selected list records to CSV file with custom field selection.

JavaScript
// Server-side code
(function() {
  // Get selected record sys_ids
  var sysIds = g_request.getParameter('sysparm_record_list');

  if (!sysIds) {
    gs.addErrorMessage('No records selected');
    return;
  }

  var recordIds = sysIds.split(',');

  // Configuration: Define fields to export
  var fieldsToExport = [
    {name: 'number', label: 'Number'},
    {name: 'short_description', label: 'Short Description'},
    {name: 'state', label: 'State'},
    {name: 'priority', label: 'Priority'},
    {name: 'assignment_group', label: 'Assignment Group'},
    {name: 'assigned_to', label: 'Assigned To'},
    {name: 'caller_id', label: 'Caller'},
    {name: 'opened_at', label: 'Opened'},
    {name: 'sys_created_on', label: 'Created'}
  ];

  // Build CSV content
  var csvContent = '';

  // Add header row
  var headers = [];
  for (var i = 0; i < fieldsToExport.length; i++) {
    headers.push(fieldsToExport[i].label);
  }
  csvContent += headers.join(',') + '\n';

  // Add data rows
  var gr = new GlideRecord('incident');
  gr.addQuery('sys_id', 'IN', recordIds.join(','));
  gr.query();

  var rowCount = 0;
  while (gr.next()) {
    var row = [];

    for (var i = 0; i < fieldsToExport.length; i++) {
      var fieldName = fieldsToExport[i].name;
      var value = '';

      // Get display value for reference fields
      if (gr[fieldName] && gr[fieldName].getDisplayValue) {
        value = gr[fieldName].getDisplayValue();
      } else {
        value = gr.getValue(fieldName) || '';
      }

      // Escape values that contain commas or quotes
      if (value.indexOf(',') !== -1 || value.indexOf('"') !== -1) {
        value = '"' + value.replace(/"/g, '""') + '"';
      }

      row.push(value);
    }

    csvContent += row.join(',') + '\n';
    rowCount++;
  }

  // Create attachment
  var fileName = 'incident_export_' + new GlideDateTime().getDisplayValue().replace(/[^0-9]/g, '') + '.csv';

  // Write to response
  var response = g_response;
  response.setContentType('text/csv');
  response.setHeader('Content-Disposition', 'attachment;filename="' + fileName + '"');
  response.getWriter().write(csvContent);

  gs.info('Exported ' + rowCount + ' incident records to CSV');

})();

How to use it

1. Create a new UI Action on your table 2. Set Name to 'Export to CSV' 3. Check 'List button' checkbox 4. Uncheck 'Client' checkbox 5. Set Order: 200 6. Customize fieldsToExport array with your desired fields 7. Add condition if needed 8. Test by selecting records and clicking Export 9. File will download automatically 10. Consider adding field validation and error handling

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.