Apache POI recording only 1 row in the spreadsheet

*爱你&永不变心* 提交于 2020-03-05 06:06:54

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/60420348/apache-poi-recording-only-1-row-in-the-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!