How to read CSV file into Array in spring boot

0
11
form dropdown in spring boot

To read a CSV file into an array in Spring Boot, you can use the following approach:

  1. Create a Bean to hold the data from each row of the CSV file. This bean should have fields that correspond to the columns of the CSV file, and setters and getters for these fields.
  2. Use the opencsv library to read the CSV file. You can add this library as a dependency in your project by including the following in your pom.xml file:
<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>4.5</version>
</dependency>
  1. In your code, use the CSVReader class from opencsv to read the CSV file. This class provides a method called readAll that returns a list of string arrays, representing the rows of the CSV file.
  2. Iterate through the list of string arrays, and for each array, create a new instance of your bean. Then use the setters of the bean to set the values from the string array. Add each bean to an array or a list.

Here is an example of how you might implement this approach:

import com.opencsv.CSVReader;

@Component
public class CsvReader {

  public List<DataBean> readCsv(String fileName) throws IOException {
    List<DataBean> dataBeans = new ArrayList<>();
    CSVReader reader = new CSVReader(new FileReader(fileName));
    String[] nextLine;
    while ((nextLine = reader.readNext()) != null) {
      DataBean dataBean = new DataBean();
      dataBean.setField1(nextLine[0]);
      dataBean.setField2(nextLine[1]);
      // Set the other fields of the bean using the remaining elements of the array
      dataBeans.add(dataBean);
    }
    reader.close();
    return dataBeans;
  }
}

This example assumes that the CSV file has a header row, and that the columns of the file correspond to the fields of the DataBean class. You can adjust the example as needed to suit the specific structure of your CSV file.

Reading a CSV file into an array in Spring Boot is a relatively straightforward process that can be accomplished using the opencsv library and a simple loop. To do this, you will need to create a bean to hold the data from each row of the CSV file, and use the CSVReader class from opencsv to iterate through the rows of the file. For each row, you can create a new instance of the bean, set the values of the fields using the values from the row, and add the bean to an array or list. Once you have read all the rows of the file, you can return the array or list as the result of your method. This approach allows you to easily read CSV files and store the data in a structured format that can be used in your application.

LEAVE A REPLY

Please enter your comment!
Please enter your name here