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

前端 未结 9 1442
情书的邮戳
情书的邮戳 2020-12-14 22:06

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
相关标签:
9条回答
  • 2020-12-14 22:13

    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
    }
    
    0 讨论(0)
  • 2020-12-14 22:13

    I'm using POI and I'm uploading a simple program. Hope this will help you.

    Note: Remember to change filepath.

    Jars details: dom4j-1.6.1.jar, poi-3.9.jar,poi-ooxml-3.9.jar, poi-ooxml-schemas-3.11.jar, xmlbeans-2.6.0.jar

    My Data in Excel Table:

    ID   NAME  LASTNAME 
    1.0  Ena   Rana 
    2.0  Meena Hanly 
    3.0  Tina  Mounce 
    4.0  Dina  Cobain 
    

    Model or Pojo: NewEmployee.java

    public class NewEmployee {
         private Double id;
         private String firstName;
         private String lastName;
    
         public NewEmployee(){}
    
        public NewEmployee(Double id, String firstName, String lastName) {
            super();
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        public Double getId() {
            return id;
        }
    
        public void setId(Double id) {
            this.id = id;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }    
    }
    

    Main Method: ExcelToObject.java

    import java.io.File;
    import java.io.FileInputStream;
    import java.util.ArrayList;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class ExcelToObject {
    
        public static void main(String[] args) {
             try
              {
                  FileInputStream file = new FileInputStream(new File("/home/ohelig/eclipse/New Worksheet.xlsx"));
    
                  //Create Workbook instance holding reference to .xlsx file
                  XSSFWorkbook workbook = new XSSFWorkbook(file);
    
                  //Get first/desired sheet from the workbook
                  XSSFSheet sheet = workbook.getSheetAt(0);
    
                  ArrayList<NewEmployee> employeeList = new ArrayList<>();
        //I've Header and I'm ignoring header for that I've +1 in loop
                  for(int i=sheet.getFirstRowNum()+1;i<=sheet.getLastRowNum();i++){
                      NewEmployee e= new NewEmployee();
                      Row ro=sheet.getRow(i);
                      for(int j=ro.getFirstCellNum();j<=ro.getLastCellNum();j++){
                          Cell ce = ro.getCell(j);
                        if(j==0){  
                            //If you have Header in text It'll throw exception because it won't get NumericValue
                            e.setId(ce.getNumericCellValue());
                        }
                        if(j==1){
                            e.setFirstName(ce.getStringCellValue());
                        }
                        if(j==2){
                            e.setLastName(ce.getStringCellValue());
                        }    
                      }
                      employeeList.add(e);
                  }
                  for(NewEmployee emp: employeeList){
                      System.out.println("ID:"+emp.getId()+" firstName:"+emp.getFirstName());
                  }
                  file.close();
              } 
              catch (Exception e) 
              {
                  e.printStackTrace();
              }
          }
    }
    
    0 讨论(0)
  • 2020-12-14 22:13

    Just found two libraries:

    • jxls-reader (but configuration is done entirely in XML... ugh!!!) http://jxls.sourceforge.net/reference/reader.html
    • excel-object-mapping this one is annotation only but unfortunately not really supported by its creator, e.g. still in "1.0-SNAPSHORT" or see the only pull request https://github.com/jittagornp/excel-object-mapping (Edit: repo has been removed since then, I found a clone here: https://github.com/pramoth/excel-object-mapping )

    Hoping it'll help someone.

    0 讨论(0)
  • 2020-12-14 22:15

    Set a look on that example that uses Apache POI to bind xlsx sheet to list of objects.

    It is a very simple example to show how to convert Microsoft Excel (xlsx) sheet to list of objects using Apache POI.

    The idea is simply to define annotation @ExcelCellInfo on the fields you want to map the sheet columns to. Then the sheet cells will be bound using reflection according to annotation attributes.

    Usage example:

    ExcelSheetDescriptor<RowClassSample> sheetDescriptor = new ExcelSheetDescriptor<>(RowClassSample.class).setHasHeader();
    List<RowClassSample> rows = ExcelUtils.readFirstSheet("pathToFile.xlsx", sheetDescriptor);
    

    And the class to bind to:

    public class RowClassSample {
    
        @ExcelCellInfo(index = 0)
        private long serial;
    
        @ExcelCellInfo(index = 1)
        private String name;
    
        @ExcelCellInfo(index = 2, cellParser = CellNumericAsStringParser.class)
        private String registrationNumber;
    
        @ExcelCellInfo(index = 3, cellParser = CellPercentageParser.class)
        private Double percentage;
    
        @ExcelCellInfo(index = 6)
        private String reason;
    
        @ExcelCellInfo(index = 4)
        private String notes;
    
        @ExcelCellInfo(index = 5, cellParser = CellBooleanYesNoArParser.class)
        private boolean approval;
    
        // getters & setters
    }
    
    0 讨论(0)
  • 2020-12-14 22:25

    You may also consider to use this tiny library excelorm

    0 讨论(0)
  • 2020-12-14 22:30

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

    0 讨论(0)
提交回复
热议问题