Attach an Excel to a record

SwarnadeepNandy
Mega Sage

I have an URL, which gives me an Excel (assume a downloadable link). I want that excel to get attached to a record in ServiceNow. We can get the such kind of link from ServiceNow's Excel web services as well. How can we achieve that. I tried something like below.

var request = new sn_ws.RESTMessageV2();
var instanceUrl = 'https://<tesinstance>.service-now.com/';
request.setEndpoint(instanceUrl + 'incident_list.do?CSV');
request.setHttpMethod('GET');

//Eg. UserName="admin", Password="admin" for this code sample.
var user = 'userName';
var password = 'password';

request.setBasicAuth(user, password);
request.setRequestHeader("Accept", "application/json");//Tried changing the Accept encoding also

var response = request.execute();
var binaryFile = response.getBody();//Receiving excel file, binary data.

var attachment = new GlideSysAttachment();

//Tried both the below lines

// attachment.writeBase64(customerImpactedGr, "Incident list.xls", "application/vnd.ms-excel", gs.base64Encode(binaryFile));
attachment.writeBase64(customerImpactedGr, "Incident list.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", gs.base64Encode(binaryFile));

Some file is getting attached, but when i tried opening the file, it seems that it is a corrupt file. Whereas this works fine with CSV file.

I tried one more thing. I converted an excel file using window.btoa() api using client side javascript and the base64 encoded file which i receive, works perfectly fine. So what i am suspecting is that gs.base64Encode() api not working correctly with binary data. Or i maynot be handling the binary data correctly.

If any one did something similar, your help will be highly appreciated.

Thanks & Regards,

Swarnadeep Nandy