Missed Team ’24? Catch up on announcements here.

×
Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

How to make changes in the script so that it can read data from csv file using csv driver

Sanjana Nalam
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
September 6, 2021

I have referred this document and installed csv driver and gave connection to csv driver.

Resources (adaptavist.com)

Previously we have used csv files and to read the data from csv files we have used the following code.

new File("path of the csv file").splitEachLine(",") {

fields ->//fields[0]-->extracted first column from the csv file 

}

Now we want to use csv driver database to fetch the data from the csv file. I want to know how to modify the above code to fetch the columns of the csv file and what all the libraries I have to import for the csv driver.

 

 

2 answers

Suggest an answer

Log in or Sign up to answer
1 vote
Martin Bayer _MoroSystems_ s_r_o__
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
September 7, 2021

Hi @Sanjana Nalam , welcome on the community. Do you really need to access the CSV as DB tables? I think it is valid for complicated CSV files and I never used it to be honest.

We use following library to read CSV files in groovy:

https://github.com/xlson/groovycsv

 It is really simple to use it...

0 votes
Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
September 9, 2021

I like opencsv for this:

Here is a simple implementation

import com.opencsv.CSVReader

@Grapes(
@Grab(group='com.opencsv', module='opencsv', version='5.5.2')
)

def reader = new CSVReader(new FileReader(new File('path to csv')))

def csvAsArrayOfMaps = reader.collect { it }.with { rows ->
def header = rows.head()
def dataRows = rows.tail()

dataRows.collect { row ->
[header, row].transpose().collectEntries()
}
}

 This this, if you file contains something like this:

colA,colB,colC
1,value1b,value1c
2,value2b,value2c

You can get the total number of rows with "csvAsArrayOfMaps.size()"

And you can get any of the rows with "csvAsArrayOfMaps[rowIndex]"

And you can get a specific column with csvAsArrayOfMaps[0].colB == 'value1b'

There are other fancier methods like "CsvToBeanBuilder" and CSVReaderHeaderAware, but I found the simplest case to be the easier to use.

More info available here: http://opencsv.sourceforge.net/

TAGS
AUG Leaders

Atlassian Community Events