Сложные условные выражения в JXLS-Reader loopbreakcondition

Мне нужна помощь с использованием jxls-reader (http://jxls.sourceforge.net/reference/reader.html).

Мне удобно зацикливать лист, где одна строка представляет конкретный объект Java, но в случае вложенных циклов я в тупике.

введите описание изображения здесь

Мне нужно сопоставить приведенный выше лист Excel со следующим pojo:

class Student {
    private String name;
    private String dob;
    private List<Class> class;
    //getters & setters
}

class Class {
    private String name;
    private String link;
    //getters & setters
}

Моя проблема заключается в определении условия взлома для чтения внутреннего объекта. Обратите внимание, что условие прерывания цикла для объекта Class требует чего-то вроде следующих:

  • Первая ячейка следующей строки не пуста ИЛИ
  • Первая ячейка следующей строки пуста И следующая ячейка текущего столбца пуста (для разрыва последней строки)

Как выразить указанное выше логическое условие в условии прерывания цикла. У меня есть следующее, но я знаю, что это неправильно:

<workbook>
    <worksheet name="Students">
        <section startRow="0" endRow="0">
            <!--Empty Header Section-->
        </section>
        <loop startRow="1" endRow="1" items="students" var="student" varType="com.test.Student">
            <section startRow="1" endRow="1">
                <mapping row="1" col="0">student.name</mapping>
                <mapping row="1" col="1">student.dob</mapping>
            </section>
            <loopbreakcondition>
                <rowcheck offset="0">
                    <cellcheck offset="0"> <!--Breaks on next empty cell--></cellcheck>
                </rowcheck>
            </loopbreakcondition>

            <loop startRow="1" endRow="1" items="student.class" var="class" varType="com.test.Class">
                <section startRow="1" endRow="1">
                    <mapping row="1" col="2">class.name</mapping>
                    <mapping row="1" col="3">class.link</mapping>
                </section>
                <loopbreakcondition>
                    <rowcheck offset="0">
                        <cellcheck offset="0"> </cellcheck>
                    </rowcheck>
                </loopbreakcondition>
            </loop>
        </loop>
    </worksheet>
</workbook>

Это вообще возможно? Есть ли другие библиотеки, которые помогут мне в этом? Или мне лучше написать свой парсер с помощью apache-poi?

Спасибо.


person jms    schedule 12.09.2020    source источник
comment
вы можете использовать apache-poi для выполнения ваших требований. пожалуйста, обратитесь к ответу ниже.   -  person Lakshan    schedule 14.09.2020


Ответы (1)


вы можете использовать apache-poi для чтения файла excel (xls или xlsx (XSSF)). для получения дополнительной информации документация по apache-poi, Apache POI-HSSF против POI-XSSF. изменил имя класса Class на StudentClass в следующем примере. потому что класс - это ключевое слово в java

попробуйте следующее решение,

Studnet.java

public class Student {
    private String name;
    private Date dob; //as per given excel file, dob is a date format
    private ArrayList<StudentClass> studentClassList;

    //getters & setters
}

StudentClass.java

public class StudentClass {
    private String name;
    private String link;

    //getters & setters
}

ExcelFileReader.java

public class ExcelFileReader() {
    private String studentName; //for store the previous student name
    private List<Student> listStudent; //for collect the students

    public void readData() {
        listStudent = new ArrayList<Student>();
        studentName = "";
        FileInputStream excelFile = new FileInputStream(new File(INPUT_EXCEL_FILE_NAME));
        Workbook workbook = new XSSFWorkbook(excelFile); //create the workbook using input excel file
        Sheet sheet = workbook.getSheetAt(0); //get the first sheet of excel file
        int rowCount = sheet.getPhysicalNumberOfRows(); //get the row count

        for(int i = 1; i < rowCount; i++) { //i initialized with 1 for exclude the first row(first row id is 0 and it hold the column names)
            if(rowCount>1){ //ignore the first row. because at this time no any student created
                listStudent.add(student); //add student into student list
                //you can use the created student in here as per your requirement
            }

            Row currentRow = sheet.getRow(i); //get current row
            if(!studentName.equals(currentRow.getCell(0).getStringCellValue())){ //if not equals current student name with previous student name then create new student entry
                Student student = new Student();
                student.setName(currentRow.getCell(0).getStringCellValue()); //first cell id is 0
                studnet.setDob(currentRow.getCell(1).getDateCellValue()); //second cell id is 1
                studentName = student.getName(); //assign the current student name to studentName variable for future validation

                if(!currentRow.getCell(2).getStringCellValue().equals(null) && !currentRow.getCell(2).getStringCellValue().equals("")){ //check the student has a class at same row(first row with new student entry)
                    StudentClass studentClass = new StudentClass();
                    studentClass.setName(currentRow.getCell(2).getStringCellValue()); //third cell id is 2
                    studentClass.setLink(currentRow.getCell(3).getStringCellValue());
                    student.getStudentClassList.add(studentClass); //add relevant StudnetClass into StudentClassList of Student. please initialized the StudentClassList in StudentClass
                }
            }else{ //this code block execute when student has more than one class
                StudentClass studentClass = new StudentClass();
                studentClass.setName(currentRow.getCell(2).getStringCellValue());
                studentClass.setLink(currentRow.getCell(3).getStringCellValue());
                student.getStudentClassList.add(studentClass);
            }
        }
    }
}
person Lakshan    schedule 13.09.2020