-2

i have 2 ArrayList of string and i want to copy their content in an excel document. I am using HSSF class to make this and if i create statically the document it works perfectly, but when i use a for loop to copy arraylist content i get IndexOutOfBoundsException exception

Here the code:

import java.io.FileOutputStream;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class createExcel {

    public void write(ArrayList<String> FirstList, ArrayList<String> SecondList) {
        try {
            String filename = "mypath\\file.xlsx" ;
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Report");

            for(int i=0; i<FirstList.size()+SecondList.size(); i++) {
                HSSFRow row = sheet.createRow((short)i);
                row.createCell(0).setCellValue(FirstList.get(i));
                row.createCell(1).setCellValue(SecondList.get(i));
            }

            FileOutputStream fileOut = new FileOutputStream(filename);
            workbook.write(fileOut);
            fileOut.close();
            System.out.println("Your excel file has been generated!");

        } catch ( Exception ex ) {
            System.out.println(ex);
        }
    }
}

Thanks

xXJohnRamboXx
  • 739
  • 3
  • 10
  • 24
  • 1
    hint: accessing by index and for loop has condition as `i – SMA Feb 11 '18 at 18:08
  • 1
    `FirstList.size()+SecondList.size()` is going to be bigger than either of the lists at some point... – ack Feb 11 '18 at 18:08

1 Answers1

1

Your error is directly related to your for loop.

for(int i=0; i<FirstList.size()+SecondList.size(); i++) {
    HSSFRow row = sheet.createRow((short)i);              
    row.createCell(0).setCellValue(FirstList.get(i));     
    row.createCell(1).setCellValue(SecondList.get(i));
}

You are looping from 0 to FirstList.size() + SecondList.size(). It's normal that at some point you get an IndexOutOfBoundsException on the smallest array. To accomplish want you want you will need 2 loops and maybe create your columns then your rows.

sleblanc
  • 38
  • 5