ScriptRunner REST Endpoints to generate excel or csv

Rauzan Fikri September 25, 2023

Hi All,

 

Any suggestion to generate excel or CSV file so user able to download the file via Get Request.

 

Thanks

1 answer

2 votes
Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
September 25, 2023

Hi @Rauzan Fikri

Could you please provide some more information, i.e. what is the source of the data that you want to use to convert into a CSV file? Is it from a database?

I am looking forward to your feedback and clarification.

Thank you and Kind regards,

Ram

Rauzan Fikri September 25, 2023

Hi @Ram Kumar Aravindakshan _Adaptavist_ 

yes correct the source data is from database then select several field to put into CSV or excel file and user can download that file.

Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
September 25, 2023

Hi @Rauzan Fikri

Thank you for the clarification.

I will try to prepare an example and get back to you once I have an update.

Thank you and Kind regards,

Ram

Like Rauzan Fikri likes this
Rauzan Fikri September 26, 2023
Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
September 26, 2023

Hi @Rauzan Fikri

I missed out one point when you mentioned:

so user able to download the file via Get Request.

Are you referring to the REST Endpoint?

Thank you and Kind regards,

Ram

Rauzan Fikri September 26, 2023

Yes correct I'm referring REST Endpoint or other ways that I can generate the excel file then user can download the file

Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
October 3, 2023

Hi @Rauzan Fikri

For your requirement, there is no simple way to access the CSV file from the REST Endpoint unless it has already been added to an issue.

If you are trying to access the CSV, an attachment in an issue, you can try this working sample code below in the ScriptRunner console. It will query the details from the database, store it in a CSV file and add the CSV file as an attachment to an issue.

import com.adaptavist.hapi.jira.issues.Issues
import com.onresolve.scriptrunner.db.DatabaseUtil

def issue = Issues.getByKey('MOCK-1')
def sqlQuery = 'select * from sample_table'

final def filePath = '/tmp'
final def fileName = 'output.csv'
def dest = new File("${filePath}/${fileName}")

def fileWriter = new FileWriter(dest)

DatabaseUtil.withSql('local_db'){ sql ->
def row = sql.rows(sqlQuery) as List<Map>
fileWriter.write(generateCSV(row))
fileWriter.close()
sql.close()
}

issue.update {
addAttachment(dest)
}
dest.delete()

static String generateCSV(List<Map> list) {
def headers = list.stream().flatMap(map -> map.keySet().stream()).distinct().collect()
def stringBuilder = new StringBuilder()
headers.each {
stringBuilder.append(it).append(', ')
}
stringBuilder.append('\n')

list.each {map ->
headers.each {
stringBuilder.append(map[it]).append(', ')
}
stringBuilder.append('\n')
}

int last = stringBuilder.lastIndexOf('\n')
if(last > 0) {
stringBuilder.delete(last, stringBuilder.length())
}

stringBuilder.toString()
}

Please note that the sample working code above is not 100% exact to your environment. Hence, you will need to make the required modifications.

Below is a screenshot of the ScriptRunner Console:-

console_config.png

Once the code is executed, the CSV file will be added to the issue that has been specified, as shown in the screenshot below:-

issue_example.png

 

Once the attachment is added to the issue, you can invoke via REST Endpoint using the sample working code below:-

import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient

import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

@BaseScript CustomEndpointDelegate delegate
getCSVFile { MultivaluedMap queryParams ->
def issueKey = queryParams.getFirst('issueKey')
def applicationProperties = ComponentAccessor.applicationProperties
final def baseUrl = applicationProperties.getString('jira.baseurl')
final def username = 'admin'
final def password = 'q'
final def headers = ['Authorization': "Basic ${"${username}:${password}".bytes.encodeBase64()}", 'Accept': 'application/json'] as Map

def http = new RESTClient(baseUrl)
http.setHeaders(headers)

def resp = http.get(path: "/rest/api/2/issue/${issueKey}") as HttpResponseDecorator

if (resp.status != 200) {
log.warn 'Commander did not respond with 200 for retrieving project list'
}

def issueJson = resp.data as Map

def dbPickerValue = issueJson['fields']['attachment']['content'] //Custom Field ID for DB Picker

Response.ok(new JsonBuilder(dbPickerValue).toPrettyString()).build()
}

Please note that the sample code above is not 100% exact to your environment. Hence, you will need to make the required modifications.

Below is a screenshot of the REST Endpoint configuration:-

rest_endpoint_config.png

When the REST Endpoint is invoked, it will display the CSV attachment link as shown in the screenshot below:-

csv_link.png

Once you click on the link, the CSV file can be downloaded.

I hope this helps to solve your question. :-)

Thank you and Kind regards,

Ram

Rauzan Fikri October 3, 2023

@Ram Kumar Aravindakshan _Adaptavist_ 

 

it's mean there's no way to create the csv file via REST Endpoint?

 

the point that I want to achieve select the data from DB and store it into CSV or excel  file.

Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
October 3, 2023

Hi @Rauzan Fikri

In your last comment, you mentioned:-

it's mean there's no way to create the csv file via REST Endpoint?

If you want to create the REST Endpoint, you can use the POST request, but where do you want to Store the CSV file? The /tmp folder?

And how do you want to access it?

Thank you and Regards,

Ram

Rauzan Fikri October 3, 2023

Hi @Ram Kumar Aravindakshan _Adaptavist_ 

 

where do you want to Store the CSV file? The /tmp folder?

Any folder that I can access via URL to download the file.

 

And how do you want to access it?

via URL path maybe

Rauzan Fikri October 9, 2023

Hi @Ram Kumar Aravindakshan _Adaptavist_ 

Did you have any sample to add a new attachment to Confluence Page from ScriptRunner Rest Endpoint?

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events