当我使用字符串列表编写excel文档时,IndexOutOfBoundsException

时间:2018-02-11 18:07:02

标签: java excel arraylist indexoutofboundsexception

我有2个字符串的ArrayList,我想在excel文档中复制他们的内容。我正在使用HSSF类进行此操作,如果我静态创建文档它完美地工作,但当我使用for循环复制arraylist内容时,我得到IndexOutOfBoundsException异常

这里是代码:

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);
        }
    }
}

由于

1 个答案:

答案 0 :(得分:1)

您的错误与您的for循环直接相关。

> A
     [,1] [,2] [,3]
[1,]    1    0   -1
[2,]    1   -3   -2
[3,]    3   -1   -1
> b
[1] -1 -1  4

您正在从0循环到FirstList.size()+ SecondList.size()。通常,在某些时候,您会在最小的数组上得到IndexOutOfBoundsException。要完成你想要的你需要2个循环,然后创建你的行然后你的行。