Paulo Roberto
Paulo Roberto

Reputation: 1548

Apache POI recording only 1 row in the spreadsheet

I am using selenium and java to scrape data on a specific site, but with the code below I can write only 1 data in the spreadsheet, it is not recording all the data in sequence as it should be.

I can't structure the loop correctly.

public void gravarDados() throws IOException {

    int i = 0;
    File localPlanilha = new File("tools/resultado_da_pesquisa.xlsx");

    FileInputStream planilhaExistente = new FileInputStream(localPlanilha);

    XSSFWorkbook plan = new XSSFWorkbook(planilhaExistente);

    XSSFSheet sheetExistente = plan.getSheetAt(0);

for (int i = 0; i < inicio; i++) {
    // Writing data
    sheetExistente.getRow(2).createCell(5).setCellValue(TitulosHoteis.get(i).getText());


    FileOutputStream fechandoArquivo = new FileOutputStream(localPlanilha);

    plan.write(fechandoArquivo);
  }
}

poi

Upvotes: 0

Views: 259

Answers (2)

tiziw
tiziw

Reputation: 128

As mentioned before you're not iterating over the rows as the row number stays the same in your code, however there is also another problem with your code. You need to check if a row exists and if it doesn't create it before you can set a cell value of that row.

It should look something like this:

for (int i = 0; i < inicio; i++) {
  Row row = sheetExistente.getRow(2+i);
  if (row == null) sheetExistente.createRow(2+i);
  sheetExistente.getRow(2 + i).createCell(5).setCellValue(TitulosHoteis.get(i).getText());
}

Upvotes: 1

shihabudheenk
shihabudheenk

Reputation: 636

Currently you are getting only the 0th element.

You need to iterate the below with a for loop

TitulosHoteis.get(i).getText());

to write the result to rows and columns.

Please modify it as below

for (int i = 0; i < inicio; i++) {
    // Writing data
    sheetExistente.getRow(i+2).createCell(5).setCellValue(TitulosHoteis.get(i).getText());

}
    FileOutputStream fechandoArquivo = new FileOutputStream(localPlanilha);

    plan.write(fechandoArquivo);

Upvotes: 4

Related Questions