Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in
Deleted user
0 / 0 points
Next:
badges earned

Your Points Tracker
Challenges
Leaderboard
  • Global
  • Feed

Badge for your thoughts?

You're enrolled in our new beta rewards program. Join our group to get the inside scoop and share your feedback.

Join group
Recognition
Give the gift of kudos
You have 0 kudos available to give
Who do you want to recognize?
Why do you want to recognize them?
Kudos
Great job appreciating your peers!
Check back soon to give more kudos.

Past Kudos Given
No kudos given
You haven't given any kudos yet. Share the love above and you'll see it here.

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

Adaptavist ScriptRunner: Export to CSV

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

5 answers

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.

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

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

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

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

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