Is there a way we could export Object to CSV in ScriptRunner?
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
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 ?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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)
*/
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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 ;-)
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Steps:
Note that it is using the Better Excel Exporter app. It is a paid app and I'm a developer.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
what do you mean, when you say object?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
No, because the script runs on the server.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Use the issue navigator export. A script can't do that because it is running on the server.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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()
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Online forums and learning are now in one easy-to-use experience.
By continuing, you accept the updated Community Terms of Use and acknowledge the Privacy Policy. Your public name, photo, and achievements may be publicly visible and available in search engines.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.