Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create rows automatically with Apache POI?

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..

like image 434
user2083481 Avatar asked Feb 18 '13 14:02

user2083481


People also ask

How do I add a row in Excel using Apache POI?

Implementing the Row Insert. For inserting m rows in the middle of an existing Excel sheet, all the rows from the insertion point to the last row should be moved down by m rows. In this step, we get the last row number by using the getLastRowNum() method and shift the rows using the shiftRows() method.

What is the purpose of getPhysicalNumberOfCells ()?

getPhysicalNumberOfCells. Gets the number of defined cells (NOT number of cells in the actual row!). That is to say if only columns 0,4,5 have values then there would be 3.

How do you create a new row in Excel in java?

getSheet("sheet1"); int rows=sh. getLastRowNum();


1 Answers

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++;
like image 160
Gagravarr Avatar answered Sep 28 '22 09:09

Gagravarr