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

前端 未结 9 1443
情书的邮戳
情书的邮戳 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:30

    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.

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

    I wanted to find a simple way to parse a xls/xlsx file to a list of pojo. After some searching i didn't find anything convenient and preferred to develop it quickly. Now i am able to get pojos by simply calling :

    InputStream is = this.getClass().getResourceAsStream("/ExcelUtilsTest.xlsx");
    List<Pojo> pojos = ExcelToPojoUtils.toPojo(Pojo.class, is);
    

    If interested take a look on it :

    https://github.com/ZPavel/excelToPojo

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

    I had the same issue, i've was aware that the implementation via the standard (Apache POI) why cost so much time so after searching and looking around, i have found a better why (JXLS-Reader)

    first of all use/import/include the library jxls-reader

        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls-reader</artifactId>
            <version>2.0.3</version>
        </dependency>
    

    then create an XML file used by the library for the correspondence between the columns and the your object attributes, this XML take as parameter an initialized list to fill it by extracted data (Employee objects) from the Excel file, in your example, it will look like :

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <workbook>
        <worksheet idx="0">
            <section startRow="0" endRow="0" />
            <loop startRow="1" endRow="1" items="employeeList" var="employee" varType="com.department.Employee">
                <section startRow="1" endRow="1">
                <mapping row="1"  col="0">employee.empNo</mapping>
                <mapping row="1"  col="1">employee.empName</mapping>
                </section>
                <loopbreakcondition>
                    <rowcheck offset="0">
                        <cellcheck offset="0"></cellcheck>
                    </rowcheck>
                </loopbreakcondition>
            </loop>
        </worksheet>
    </workbook>
    

    Then in Java, initialize the list of the Employees (where the result of parsing will be included), then call the JXLS reader by the input Excel file and the XML mapping, it will look like:

    package com.department;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.commons.io.IOUtils;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.jxls.reader.ReaderBuilder;
    import org.jxls.reader.ReaderConfig;
    import org.jxls.reader.XLSReader;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.xml.sax.SAXException;
    
    
    public class ExcelProcessor {
    
        private static Logger logger = LoggerFactory.getLogger(ExcelProcessor.class);
    
        public void parseExcelFile(File excelFile) throws Exception{
            final List<Employee> employeeList = new ArrayList<Employee>();
            InputStream xmlMapping = new BufferedInputStream(ExcelProcessor.class.getClassLoader().getResourceAsStream("proBroMapping.xml"));
            ReaderConfig.getInstance().setUseDefaultValuesForPrimitiveTypes(true);
            ReaderConfig.getInstance().setSkipErrors(true);
            InputStream inputXLS;
            try{
                XLSReader mainReader = ReaderBuilder.buildFromXML(xmlMapping);
                inputXLS = new BufferedInputStream(new FileInputStream(excelFile));
                final Map<String, Object> beans = new HashMap<String, Object>();
                beans.put("employeeList", employeeList);
                mainReader.read(inputXLS, beans);
                System.out.println("Employee data are extracted successfully from the Excel file, number of Employees is: "+employeeList.size());
            } catch(java.lang.OutOfMemoryError ex){
                // Case of a very large file that exceed the capacity of the physical memory
                   ex.printStackTrace();
                throw new Exception(ex.getMessage());
            } catch (IOException ex) {
                logger.error(ex.getMessage());
                throw new Exception(ex.getMessage());
            } catch (SAXException ex) {
                logger.error(ex.getMessage());
                throw new Exception(ex.getMessage());
            } catch (InvalidFormatException ex) {
                logger.error(ex.getMessage());
                throw new Exception(ex.getMessage());
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
    
        }
    
    }
    

    Hope this helps anyone having such a problem !

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