How to generate excel file from a script in ServiceNow

karishmashaik
Kilo Expert

Hi

we need to generate Excel sheet  a request to be placed in a file to be auto generated (possibly xls, xlsx etc. format) as an attachment & should be attached to the Requested item submitted.

We did had something similar to be done for an request item which was achieved by using the below snippet in the Runscript activity 

All that is required is to retrieve the list of variables & then use the Write functionality of GlideSysAttachment API class.

i am trying this script pls help me on this :

var Headers = ["Number","Caller","Short Desc","Assignment Group", "Assigned To"];
var fileName = 'Incidents.xls';
var xlsData = ''; //The variable xlsData will contain a string which is used to build the xls file contents
for (var i = 0; i < Headers.length; i++) { //Build the Headers
xlsData = xlsData + '"' + Headers[i] + '"' + ',';
}
xlsData = xlsData+"\r\n";

var gr = new GlideRecord("incident");
gr.addActiveQuery();
gr.query();
while(gr.next()) {
xlsData = xlsData + '"' + gr.number + '",' + '"' + gr.caller_id.getDisplayValue() + '",' + '"' + gr.short_description+'",' + '"' + gr.assignment_group.getDisplayValue() + '",' + '"' + gr.assigned_to.getDisplayValue() + '"';
xlsData = xlsData+"\r\n";
}

//attach the file to a record.
var grRec = new GlideRecord("incident");
grRec.addQuery("sys_id","00b4939bdb010110c8cf9026ca9619e7");
grRec.query();
if(grRec.next()){
var grAttachment = new GlideSysAttachment();
grAttachment.write(grRec, fileName,'application/xls',xlsData);
}

for example

This would then print data in Excel in format as above

If at all data is required to be printed in the format as above

image

with all Variable questions in Column A & its corresponding values in column B (something in tabular form) then all you need is to use the above snippet

12 REPLIES 12

It's done in the "Begin File" step. Just make sure you set the File Name as "...csv".

find_real_file.png

 

If helpful or correct, please indicate so!

Hello Mattias Johnsson,

Thank you very much for your kind reply.
Youe are awesome!
It's working and I can automatically export target table's records for CSV file.

Thank you:)
Chen

 

Hi Mattias,

 

Can you also please share the screenshots on how to attach the built file in step 7 to the RITM record? 

 

Thank you,

Swathi

Your solution requires Integration Hub. Is this license free? 

Well, the "Utility Actions" has a Dependency on "ServiceNow IntegrationHub Runtime". That comes with Integration Hub Starter, that has no cost. However, you will still need the license for it (as compared to for instance old Orchestration licenses).

 

That said, if you have Integration Hub starter or greater, you're good to go.

 

If helpful or correct, please indicate so!