Is there a way we could export Object to CSV in ScriptRunner?
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.
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()
Steps:
Note that it is using the Better Excel Exporter app. It is a paid app and I'm a developer.
This should do it:
// This is the CSV library Atlassian has built into Jira// See https://wush.net/svn/mindprod/com/mindprod/csv/CSVWriter.javaimport com.mindprod.csv.CSVWriter// Convert a list of maps to a CSV stringdef 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.ComponentAccessorimport com.atlassian.jira.security.groups.GroupManagerimport com.atlassian.jira.user.ApplicationUserimport com.atlassian.jira.issue.MutableIssueimport com.atlassian.jira.issue.Issueimport java.io.Fileimport com.atlassian.jira.issue.attachment.CreateAttachmentParamsBeanimport com.atlassian.jira.security.roles.RoleActorimport org.apache.log4j.Categoryimport com.atlassian.jira.component.ComponentAccessorimport com.atlassian.jira.security.login.LoginManagerimport java.text.SimpleDateFormat;import java.util.Date;import com.atlassian.jira.bc.group.search.GroupPickerSearchServiceimport com.atlassian.crowd.embedded.api.GroupCategory 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.ComponentAccessorimport com.atlassian.jira.security.groups.GroupManagerimport com.atlassian.jira.user.ApplicationUserimport com.atlassian.jira.issue.MutableIssueimport com.atlassian.jira.issue.Issueimport java.io.Fileimport com.atlassian.jira.issue.attachment.CreateAttachmentParamsBeanimport com.atlassian.jira.security.roles.RoleActorimport org.apache.log4j.Categoryimport com.atlassian.jira.component.ComponentAccessorimport com.atlassian.jira.security.login.LoginManagerimport java.text.SimpleDateFormat;import java.util.Date;import com.atlassian.jira.bc.group.search.GroupPickerSearchServiceimport com.atlassian.crowd.embedded.api.GroupCategory 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 ;-)
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.
@kiran kumar did you get any solution for your request?
Hello, does this stills working? I updated the path but it didn't do the trick
It looks like you're new here. Sign in or register to get started.