Adaptavist ScriptRunner: Export to CSV

kiran kumar June 24, 2019

Is there a way we could export Object to CSV in ScriptRunner?

6 answers

2 votes
Alex van Vucht (GLiNTECH)
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
September 8, 2020

This should do it:

// This is the CSV library Atlassian has built into Jira
// See https://wush.net/svn/mindprod/com/mindprod/csv/CSVWriter.java

import com.mindprod.csv.CSVWriter

// Convert a list of maps to a CSV string
def mapsToCSV(mapList) {

// Get keys from all maps and build a header row
def headerSet = new LinkedHashSet()
mapList.each { headerSet.addAll(it.keySet()) }
def headers = headerSet.toArray()

def sw = new StringWriter()
def csv = new CSVWriter(sw)

// Add header row
headers.each {csv.put(it.toString())}
csv.nl()

// Add rows - put in empty string if a header key doesn't exist in a row
mapList.each { row ->
headers.each {
csv.put(row.get(it)?.toString() ?: '')
}
csv.nl()
}
csv.close()
return sw.toString()
}

Example usage:

def myMapList = [[
'key': 'BUSINESS-1',
'summary': 'My first issue',
"components":[{"id":"10000","name":"First component"}]
],[
'key': 'SCRUM-1',
'summary': 'My first backlog item',
'storypoints': 10
]]
String csvString = mapsToCsv(myMapList)

Example output:

key,summary,components,storypoints
BUSINESS-1,"My first issue","[[id:10000, name:First component]]",
SCRUM-1,"My first backlog item",,10
1 vote
Sylvain Leduc April 22, 2021

I'm using this script that works very well but I'm not able to set a specific path like the method above :

def filePath = "/some/path/test.csv"
new File(filePath).createNewFile()

 
Script :

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.groups.GroupManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.Issue
import java.io.File
import com.atlassian.jira.issue.attachment.CreateAttachmentParamsBean
import com.atlassian.jira.security.roles.RoleActor
import org.apache.log4j.Category
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.login.LoginManager
import java.text.SimpleDateFormat;
import java.util.Date;

import com.atlassian.jira.bc.group.search.GroupPickerSearchService

import com.atlassian.crowd.embedded.api.Group
Category log = Category.getInstance("com.onresolve.jira.groovy")
log.setLevel(org.apache.log4j.Level.DEBUG)

def userManager = ComponentAccessor.getUserManager()
def userList = userManager.getAllApplicationUsers()
def groupManager = ComponentAccessor.getGroupManager()
def loginManager = ComponentAccessor.getComponentOfType(LoginManager.class)
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy hh:mm");
// Enter issue name where the attachment will be added
// Issue issue = ComponentAccessor.getIssueManager().getIssueObject("ISSUE-nb")
def mapcsvLine = [:]
String csvReturn = ""

int i=0
// for (Group group in groupList){
for (ApplicationUser user in userList){
List csvLine = new ArrayList<String>()
csvLine.add(user.getUsername())
csvLine.add(user.getEmailAddress())
csvLine.add(user.getDirectoryId().toString())
Long lastLoginTime = loginManager.getLoginInfo(user.name).getLastLoginTime()
if (lastLoginTime == null){
csvLine.add("null")
}else{
Date date=new Date(lastLoginTime);
csvLine.add(df2.format(date))
}
csvLine.add(user.isActive().toString())
csvLine.add(groupManager.getGroupNamesForUser(user).toString())
if(csvLine.size()>0){
mapcsvLine.put(i,csvLine)
}
i++
}


csvReturn +="username;email;directoryId;Lastlogindate;status;groups \n"
for (Map.Entry<Integer, List> entry : mapcsvLine.entrySet()) {
csvReturn += entry.getValue()[0].toString() + ";"
csvReturn += entry.getValue()[1].toString() + ";"
csvReturn += entry.getValue()[2].toString() + ";"
csvReturn += entry.getValue()[3].toString() + ";"
csvReturn += entry.getValue()[4].toString() + ";"
csvReturn += entry.getValue()[5].toString()
csvReturn += " \n "
}
/* Below line will export the temporary file in this folder "/atlassian/jira/application/current/temp/<RANDOMNAME>.csv" */
File csvFile = File.createTempFile("exportTEST",".csv")
csvFile.append(csvReturn)
log.debug(csvFile.getAbsolutePath())
// Uncomment below line to add the attachment to the issue number specified above
/*
def attachmentManager = ComponentAccessor.getAttachmentManager()
def user = ComponentAccessor.getJiraAuthenticationContext()?.getUser()
def bean = new CreateAttachmentParamsBean.Builder()
.file(new File(csvFile.getAbsolutePath()))
.filename("export.csv")
.contentType("csv")
.author(user)
.issue(issue)
.build()
attachmentManager.createAttachment(bean)
*/

 Any idea how to specify a path in the home directory ?

Sylvain Leduc April 22, 2021

Found it, with the specific path :

File csvFile = new File("/jira/home-data/export/Export_Users.csv");
csvFile.append(csvReturn)
log.debug(csvFile.getAbsolutePath())

Full script updated :

 

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.groups.GroupManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.Issue
import java.io.File
import com.atlassian.jira.issue.attachment.CreateAttachmentParamsBean
import com.atlassian.jira.security.roles.RoleActor
import org.apache.log4j.Category
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.login.LoginManager
import java.text.SimpleDateFormat;
import java.util.Date;

import com.atlassian.jira.bc.group.search.GroupPickerSearchService

import com.atlassian.crowd.embedded.api.Group
Category log = Category.getInstance("com.onresolve.jira.groovy")
log.setLevel(org.apache.log4j.Level.DEBUG)

def userManager = ComponentAccessor.getUserManager()
def userList = userManager.getAllApplicationUsers()
def groupManager = ComponentAccessor.getGroupManager()
def loginManager = ComponentAccessor.getComponentOfType(LoginManager.class)
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy hh:mm");
// Enter issue name where the attachment will be added
// Issue issue = ComponentAccessor.getIssueManager().getIssueObject("ISSUE-nb")
def mapcsvLine = [:]
String csvReturn = ""

int i=0
// for (Group group in groupList){
for (ApplicationUser user in userList){
List csvLine = new ArrayList<String>()
csvLine.add(user.getUsername())
csvLine.add(user.getEmailAddress())
csvLine.add(user.getDirectoryId().toString())
Long lastLoginTime = loginManager.getLoginInfo(user.name).getLastLoginTime()
if (lastLoginTime == null){
csvLine.add("null")
}else{
Date date=new Date(lastLoginTime);
csvLine.add(df2.format(date))
}
csvLine.add(user.isActive().toString())
csvLine.add(groupManager.getGroupNamesForUser(user).toString())
if(csvLine.size()>0){
mapcsvLine.put(i,csvLine)
}
i++
}


csvReturn +="username;email;directoryId;Lastlogindate;status;groups \n"
for (Map.Entry<Integer, List> entry : mapcsvLine.entrySet()) {
csvReturn += entry.getValue()[0].toString() + ";"
csvReturn += entry.getValue()[1].toString() + ";"
csvReturn += entry.getValue()[2].toString() + ";"
csvReturn += entry.getValue()[3].toString() + ";"
csvReturn += entry.getValue()[4].toString() + ";"
csvReturn += entry.getValue()[5].toString()
csvReturn += " \n "
}
/* Below line will export the file in this folder "/jira/home-data/export/" */
File csvFile = new File("/jira/home-data/export/Export_Users.csv");
csvFile.append(csvReturn)
log.debug(csvFile.getAbsolutePath())
// Uncomment below line to add the attachment to the issue number specified above
/*
def attachmentManager = ComponentAccessor.getAttachmentManager()
def user = ComponentAccessor.getJiraAuthenticationContext()?.getUser()
def bean = new CreateAttachmentParamsBean.Builder()
.file(new File(csvFile.getAbsolutePath()))
.filename("export.csv")
.contentType("csv")
.author(user)
.issue(issue)
.build()
attachmentManager.createAttachment(bean)
*/
Sylvain Leduc May 7, 2021

Hello,
Updating the previous script, to get a filename with current date/time.
Replacing :

"

File csvFile = new File("/jira/home-data/export/Export_Users.csv");

"

With :

Date datecsv = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss") ;
File csvFile = new File("/srv/jira-home/export/Export_Users_"+ dateFormat.format(datecsv) + ".csv");

Works for me ;-)

1 vote
Aron Gombas _Midori_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
December 9, 2019

Steps:

  1. Export the change history to Excel (details)
  2. It should look like the spreadsheet below
  3. Save the Excel spreadsheet to CSV using the Excel feature

Note that it is using the Better Excel Exporter app. It is a paid app and I'm a developer.

jira-issues-selected-fields-with-change-history

1 vote
Tomas Gustavsson
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
June 24, 2019

what do you mean, when you say object?

kiran kumar June 24, 2019

I need to pull issue keys and issue history which contains the statuses FROM and TO and also userkey. 

I want to create an object to stitch the properties I need, so I could export them into a CSV file.

Venkataramana November 30, 2022

@kiran kumar did you get any solution for your request?

0 votes
Wajdan June 17, 2022

Hi Guys,

 

Can we use the same script to download the csv file in the browser/client side instead of saving it over the server?

Nic Brough -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.
June 18, 2022

No, because the script runs on the server.

Wajdan June 20, 2022

Hi Nic. Thanks alot for your response.

My use case requires the file to be exported to user computer. Is there any way we can achieve that?

Thanks in advance

Nic Brough -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.
June 21, 2022

Use the issue navigator export.  A script can't do that because it is running on the server.

0 votes
Ilya Turov
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
June 26, 2019

assuming you got your "object" ready here's basic concept of how to export it:

def filePath = "/some/path/test.csv"
new File(filePath).createNewFile()
PrintWriter writer = new PrintWriter(filePath, "UTF-8")
def someInfo = [1, 2, 3]
writer.println("head1;head2;head3")
someInfo.each {
writer.println("$it;line;test")
}
writer.close()

Suggest an answer

Log in or Sign up to answer