How to export data to CSV from a widget

TT3
Kilo Guru

I have a widget and it shows data from a database view based on the filter provided in the widget. The widget also adds calculative columns and data. The calculations are pretty complex and we can't do it as part of report (this is because report provides very basic calculations).

The widget is clone of OOB data.table widget. As you may know, it uses data.list array to load data.

As per requirements, we are able to show the data, however, I do need a functionality / button so that user can export the data in the array (data.list) to CSV file.

Note that this is not a traditional ServiceNow table which user can export by right click as there are some calculated column - which does not exist in the database view.

Considering this, it seems I may have to use (if available) Angular function to export if not then I will go with Javascript function.

 

Any pointer/reference/idea on how to do that?

6 REPLIES 6

-O-
Kilo Patron
Kilo Patron

I'm sorry, but how can an array be server side?

Server side are just two things:

- what is being executed at a given time, e.g. when the data is prepared for the widget that is just being loaded into a browser or

- what is in a table.

 

If it is the 1st case, than that array exists server side only while the Server script (of the Widget is being executed), by the time the page is shown to the user in the browser all that no longer exists.

 

If it is the 2nd case, than the original solution applies; just create a view that includes all the data you want and add parameter sysparm_view with the appropriate value (the name of the special view you would create).

 

Also if the case is the 1st, that means that the data is crunched server side not just for the fun of it, but to send it to client side through c.data. If that is the case, than the alternate solution, using Blob can be used.

 

Just add a

 

console.log(c.data);

 

statement to the client controller, as much near the top as possible, save, refresh the page and check the browser's developer console for the logged object. Look through it's properties, see can you spot the data in there?

-O-
Kilo Patron
Kilo Patron

Another option would be the use of File(). The advantage would be that you get the option to set the name of the downloaded file:

	const csv = new File(['Col_1,Col_2,Col_3\r\nData 1,Data 2,Data 3\r\nData 4,Data 5,Data 6\r\n'], 'data.csv', { 'type': 'text/csv', });