Skip to main content

How to read from CSV file in Java

We can read data from a Microsoft Excel CSV file, where all the values will be column separated, to do this we will use a third party jar i.e OpenCSV.

OpenCSV

OpenCSV is a lightweight java CSV parser. OpenCSV provides most of the basic features for CSV parsing. Some of the important classes in OpenCSV parser are;

CSVReader: This is the most important class in OpenCSV. CSVReader class is used to parse CSV files. We can parse CSV data line by line or read all data at once.
CSVWriter: CSVWriter class is used to write CSV data to Writer implementation. 
CsvToBean: CsvToBean is used when you want to convert CSV data to java objects.
BeanToCsv: BeanToCsv is used to export Java beans to CSV file.

OpenCSV Maven Dependency

Add OpenCSV jar using below maven dependency in POM.XML file, please refer the latest version from https://mvnrepository.com/artifact/com.opencsv/opencsv

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>3.8</version>
</dependency>

There are two ways to read a csv file using OpenCSV
  1. Reading into an array of strings
  2. Reading into beans


Sample data :





Create java bean class to hold CSV data and all fields mention in POJO class should match the column name of CSV file and they are case sensitive.

package com.Excel;

import com.opencsv.bean.CsvBindByName;

public class Employee {
    @CsvBindByName
    private String Empid;
    @CsvBindByName
    private String name;
    @CsvBindByName
    private String salary;
    @CsvBindByName
    private String valid;
    
    public String getEmpid() {
        return Empid;
    }
    public void setEmpid(String empid) {
        Empid = empid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSalary() {
        return salary;
    }
    public void setSalary(String salary) {
        this.salary = salary;
    }
    public String getValid() {
        return valid;
    }
    public void setValid(String valid) {
        this.valid = valid;
    }
}

we are using @CsvBindByName annotation which identify all columns by name in CSV file.

Main class to read our CSV file.

package com.Excel;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import com.opencsv.bean.CsvToBeanBuilder;

public class ReadEXcel {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) {
        List<Employee> beans;
        try {
            beans = new CsvToBeanBuilder(new FileReader("test.csv")).withType(Employee.class).build().parse();
            for (Employee employee : beans) {
                System.out.println(employee.getEmpid());
                System.out.println(employee.getName());
                System.out.println(employee.getSalary());
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

This jar gives us freedom of type conversions (wrapped and unwrapped primitives and Strings) occur automatically which is a big relief as a programmer you don't bother about the type in excel as it will handle by your POJO class which you have created.




Comments

Popular posts from this blog

Extent report plugin for cucumber framework

Extent Reports  are the most popular  reporting  used with Selenium. ExtentReport API makes our life easy to generate interactive  report  with simple configuartions. It supports almost all Java and .NET test frameworks such as TestNG , JUnit , NUnit etc Here we are discussing about  a plugin which is build on  Extent Report specially for Cucumber. This plugin is used to simple out the implementation of  Extent Report  in  Cucumber Framework .  We are creating a maven project to implement the integration of our plugin with cucumber 1. Create new maven project in any tool eclipse/sts/intellij 2. Open pom.xml and update below entries. Step 1 : Add Cucumber Extent Reporter library to Maven Project Add  cucumber-extentsreport <dependency>      <groupId> com.vimalselvam </groupId>      <artifactId> cucumber-extentsreport </artif...

java: You aren't using a compiler supported by lombok, so lombok will not work and has been disabled.

  In order to make projects compile with the existing builds of Lombok processor, as a workaround you can use the flag -Djps.track.ap.dependencies=false which should be added to File | Settings | Build, Execution, Deployment | Compiler | Build process VM options field. This will disable collection of dependencies specified by an annotation processor when Filer methods are called

Execution default of goal org.springframework.boot:spring-boot-maven-plugin:1.2.3.RELEASE:repackage failed: Unable to find main class

Solutions:  Solution 1 : You needed to change the packaging parameter to jar from pom. Also, the repositories , pluginRepositories , the maven-compiler-plugin and the spring-boot-maven-plugin's version and executions weren't needed. Solution 2:  Try mvn install and see if it works Solution 3: Preview: <properties> <!-- The main class to start by executing java -jar --> <start-class> com.mycorp.starter.HelloWorldApplication </start-class> </properties> Solution 4: Enable the main() method in your Application.java. Configure spring-boot-maven-plugin to specify the class with the main class (Spring should find it anyway if you have one, but good to be explicit): Preview: <plugin> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-maven-plugin </artifactId> <version> ${spring-boot-version} </version>...