Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert my xlsx sheet to java object using Apache POI

can any one suggest me to convert my xlsx sheet to java object using Apache POI.

eq, my excel sheet contains two columns

  • emp_no emp_name
  • 01 anand
  • 02 kumar

and my java object

Employee{
String empNo;
String empName; 
}

Now I want to convert my excel sheet to java object. I have tried in internet but most of the tutorials talks about iterate each row and assign values to each member sin the object. Is there any functionality like Marshaller and UnMarshaller in JAXB xml parser which convert directly.

Thanks in advance.

like image 333
Anand Avatar asked Feb 25 '14 13:02

Anand


3 Answers

For the given Scenario, I am assuming that each row of the sheet is representing an employee of which say first Column is keeping employee Number and second column is keeping Employee Name. so you can use the following:

Employee{
  String empNo;
  String empName; 
}

Create a method of assigning the Employee information as

assignEmployee(Row row){
    empNo = row.getCell(0).toString();
    empName = row.getCell(1).toString();
}

or if you want you can create a constructor for the same.

Now you just need to iterate over each row to get/use the information using the above method.

Employee emp = new Employee();
Iterator<Row> itr = sheet.iterator();
    while(itr.hasNext()){
       Row row = itr.next();
       emp.assignEmployee(row);
      //  enter code here for the rest operation
}
like image 152
Sankumarsingh Avatar answered Nov 11 '22 10:11

Sankumarsingh


Try this library internally using Apache POI for converting from excel to POJO.: Poji

like image 14
Balaban Mario Avatar answered Nov 11 '22 10:11

Balaban Mario


Check the below repo. It was developed by keeping "ease of use" in head. https://github.com/millij/poi-object-mapper

Initial version has been published to Maven Central.

<dependency>
    <groupId>io.github.millij</groupId>
    <artifactId>poi-object-mapper</artifactId>
    <version>1.0.0</version>
</dependency>

Works similar to Jackson. Annotate your bean like below..

@Sheet
public class Employee {
    // Pick either field or its accessor methods to apply the Column mapping.
    ...
    @SheetColumn("Age")
    private Integer age;
    ...
    @SheetColumn("Name")
    public String getName() {
        return name;
    }
    ...
}

And to read..

...
final File xlsxFile = new File("<path_to_file>");
final XlsReader reader = new XlsReader();
List<Employee> employees = reader.read(Employee.class, xlsxFile);
...

As it stands, all primitive data types are supported. Still working on adding support for Date, Formula etc..

Hope this helps.

like image 6
Milli Avatar answered Nov 11 '22 12:11

Milli