Search code examples
javaapache-poiexport-to-excel

Writing arraylist of a class in to excel java


I am receiving an Arraylist from db and I need to write it to an Excel sheet. Data received: Arraylist . I need to also maintain the order . I will take care of data types while setting to the excel. GDTPolicy Class has around 90 attributes. How do I iterate through the GDTPolicy and set the data to excel? Or do i need to export in different data type from db? . Any suggestions welcome

ArrayList<GDTPolicy> data= gdtRepository.fetchbyDate();

    Workbook book = new XSSFWorkbook();
        org.apache.poi.ss.usermodel.Sheet sheet = book.createSheet("Quotation");

        for (int i = 0; i < data.size(); i++) {
            ArrayList<String> rows = excelData.get(i);
            // GDTPolicy= data.get(i);
            Row row = sheet.createRow(i);
            for (int j = 0; j < rows.size(); j++) {
                Cell data = row.createCell(j);
                data.setCellValue(rows.get(j));
            }
        }

Solution

  • If you don't want to set the cell.setValue for each of the properties, one option you have is to use reflection, something like this:

    Field [] fields = rows.get(j).getClass().GetDeclaredFields();
    
    int countField = 0;
    for (Field field : fields){
        Cell data = row.createCell(countField);
        data.setCellValue(field.get(rows.get(j))); 
        countField = countField +1;  
    }
    

    https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getDeclaredField%28java.lang.String%29