Mapping CSV to JavaBeans Using OpenCSV
OpenCSV provides classes to map CSV file to a list of Java-beans. CsvToBean class is used to map CSV data to JavaBeans. The CSV data can be parsed to a bean, but what is required to be done is to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean. HeaderColumnNameTranslateMappingStrategy is the mapping strategy which maps the column id to the java bean property.
- First add OpenCSV to the project.
- For maven project, include the OpenCSV maven dependency in pom.xml file.
- For Gradle Project, include the OpenCSV dependency.
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
- You can Download OpenCSV Jar and include in your project class path.
- Mapping CSV to JavaBeans Mapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:
- Create a Hashmap with mapping between the column id and bean property.
Map mapping = new HashMap(); mapping.put("column id ", "javaBeanProperty");
- Then add all the column id of csv file with their corresponding javabean property.
- Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.
HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy(); strategy.setType(JavaBeanObject.class); strategy.setColumnMapping(mapping);
- Create the object of CSVReader and CsvToBean class
String csvFilename = "data.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); CsvToBean csv = new CsvToBean();
- Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.
List list = csv.parse(strategy, csvReader);
Example: Let’ s convert csv file containing Student data to Student objects having attribute Name, RollNo, Department, Result, Pointer.
StudentData.csv: name, rollno, department, result, cgpa amar, 42, cse, pass, 8.6 rohini, 21, ece, fail, 3.2 aman, 23, cse, pass, 8.9 rahul, 45, ee, fail, 4.6 pratik, 65, cse, pass, 7.2 raunak, 23, me, pass, 9.1 suvam, 68, me, pass, 8.2
First create a Student Class with Attributes Name, RollNo, Department, Result, Pointer. Then Create a main class which map csv data to JavaBeans object. Programs:
Student [Name=amar, RollNo=42, Department=cse, Result=pass, Pointer=8.6] Student [Name=rohini, RollNo=21, Department=ece, Result=fail, Pointer=3.2] Student [Name=aman, RollNo=23, Department=cse, Result=pass, Pointer=8.9] Student [Name=rahul, RollNo=45, Department=ee, Result=fail, Pointer=4.6] Student [Name=pratik, RollNo=65, Department=cse, Result=pass, Pointer=7.2] Student [Name=raunak, RollNo=23, Department=me, Result=pass, Pointer=9.1] Student [Name=suvam, RollNo=68, Department=me, Result=pass, Pointer=8.2]
Reference: OpenCSV Documentation, CsvTOBean Documentation, MappingStrategy
Please Login to comment...