Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
4,293,292
Community Members
 
Community Events
165
Community Groups

Adaptavist ScriptRunner: Export to CSV

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

6 answers

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

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

what do you mean, when you say object?

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.

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?

No, because the script runs on the server.

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

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

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 ?

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)
*/

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 ;-)

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
TAGS

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you