Excel file with list of java object

Store the excel data in java object list, its simple with using poiji and Apache poi.

These are Maven dependency  add these in pom.xml file.

                <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.github.ozlerhakan</groupId>
<artifactId>poiji</artifactId>
<version>1.20.0</version>
</dependency>

create a model to map excel columns with object, each row will become an object and all data from excel will become list of object.

ExcelMatchModel.java 

import com.poiji.annotation.ExcelCellName;
package com.example.file.upload;
import java.io.Serializable;
import com.poiji.annotation.ExcelCellName;

public class ExcelMatchModel implements Serializable {
private static final long serialVersionUID = 1781689208090743584L;

/**

*/

@ExcelCellName("name")
String name;

@ExcelCellName("email")
String mail;

@ExcelCellName("id")
String id;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getMail() {
return mail;
}

public void setMail(String mail) {
this.mail = mail;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

@Override
public String toString() {
return "ExcelMatchModel [name=" + name + ", mail=" + mail + ", id=" + id + "]";
}

}

Here i am mapping excel columns using @ExcelCellName
After creating model to map with the list need to write some logic that will be either go to service class or controller, i am writing in my controller.

@RequestMapping(value = "/uploadexcel")
private @ResponseBody List<ExcelMatchModel> uploadExcel() throws FileNotFoundException {
File file = new File("C:\\Users\\"+System.getProperty("user.name")+"\\Downloads\\tesmxl.xlsx");
List<ExcelMatchModel> list = Poiji.fromExcel(file, ExcelMatchModel.class);
return list;
}

I have kept my excel file to download folder so provided this path (C:\\Users\\"+System.getProperty("user.name")+"\\Downloads\\tesmxl.xlsx) it can be anywhere,

and make sure about @ResponseBody, it should be available otherwise javax.servlet.ServletException: Circular view path will hit.

Excel :


Output :

[{"name":"abc","mail":"abc@mail.com","id":"1"},{"name":"xyz","mail":"xyz@mail.com","id":"2"},{"name":"kkk","mail":"kkk@mail.com","id":"3"}]

Post a Comment

Previous Post Next Post