Convert table records to excel using background script

Hello ServiceNow Geeks,

This article is specifically prepared for you to provide you a script to covert table records to excel sheet using background script in ServiceNow. Here is the code for same requirement-

var output = "Number,ZILS,Attachment_Name";// declaring the headers in xls file
var table = "sys_attachment";
var recordId = "";

var gr = new GlideRecord(table);
gr.addEncodedQuery("table_name=kb_template_kcs_article^sys_created_by=testUser^ORsys_created_by=12345"); //filter to find the created by in attachmnet table

var count = 0;
while ( {
	var rec = new GlideRecord('kb_template_kcs_article');
	output += "\n" + rec.number + "," + rec.u_km_id + "," + gr.file_name;
	if (!recordId) {
		recordId = gr.sys_id;


function writeAttachmentFile(data) {
   var attachment = new Attachment();
   var attachmentRec = attachment.write(table, recordId, "export.csv", "text/csv", data);

I hope this will help you in fulfilling your requirement too. Please do comment your requirement and script which may help other developers of our ServiceNow community. Do share your this article and let us know how we can improve our posts.

Leave a Reply

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