Generate CSV File from a Search

Solution

Below code defines how to generate a CSV file from a Search

function execute(scriptContext) {‌
    	var mySearch = search.load({‌
    		id: '47'
    	})
    	
		//Run saved search
    	var mySearchResultSet = mySearch.run();
    	log.debug('Results...',mySearchResultSet)
		
		//Headers of CSV File separated by commas and ends with a new line (\r\n)
		var csvFile = 'Internal ID,Item Name,Average Cost\r\n';

		//Iterate through each result
		mySearchResultSet.each(iterator);
			
			function iterator(resultObject){‌
				
				//Get value returned for Internal ID
				var internalid = resultObject.getValue({‌
					name: 'internalid'
				})
				//Get value returned for Item ID
                		var itemid = resultObject.getValue({‌
					name: 'itemid'
				})
				//Get value returned for Average Cost
                		var averagecost = resultObject.getValue({‌
					name: 'averagecost'
				})
				
				//Add each result as a new line on CSV
				csvFile += internalid+','+itemid+','+averagecost+'\r\n'
				return true;
				
			}
		
		//Variable for datetime
		var date = new Date();
		
		//Creation of file
    		var fileObj = file.create({‌
			//To make each file unique and avoid overwriting, append date on the title
			name: 'Saved Search Result - ' + date.toLocaleDateString() +'.csv',
			fileType: file.Type.CSV,
			contents: csvFile,
			description: 'This is a CSV file.',
			encoding: file.Encoding.UTF8,
			folder: 429
    		});
		
		//Save the CSV file
		var fileId = fileObj.save()
    		log.debug('File ID...',fileId)
    }

    return {‌
        execute: execute
    };
    
});

Leave a comment

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