How to create rows automatically with Apache POI?

user2083481 picture user2083481 · Feb 18, 2013 · Viewed 10.3k times · Source

I'm working in a project in Java and I Need to create one xls file with some information. So, depending on the amount of information, I need to create automatically Rows and cells to put this information..

Example: if the input documents has 13 Site Information, I need to create 13 Rows with 4 cell.. How I do it? .. my attempt to code:

Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("new sheet");

    int numberrows = Integer.parseInt(JOptionPane.showInputDialog(null, "numbers of sites??"));


    String siteName = JOptionPane.showInputDialog(null, "Site name");
    String rncname = JOptionPane.showInputDialog(null, "RncName");


    for (int i = 0; i < numberrows; i++) {
        HSSFRow linha =  (HSSFRow) sheet.createRow(i);

        linha.createCell((short) i ).setCellValue(siteName);
        linha.createCell((short) i ).setCellValue(rncname);

    }

Thanks in advance..

Answer

Gagravarr picture Gagravarr · Feb 18, 2013

Can you not just do something simple like:

int nextRow = 12;

Row r = sheet.getRow(nextRow);
if (r == null) {
    r = sheet.createRow(nextRow);
}

Cell c = r.getCell(2, Row.CREATE_NULL_AS_BLANK);
c.setCellValue("My String");

nextRow++;