Daniela Morais
Daniela Morais

Reputation: 2237

Why can't set a value for a row and column with the Apache POI?

I need to set a value for a specific row and column of the spreadsheet, but I get a null pointer before even i = 1. I've tried changing the code but this error keeps happening and I have no more idea why.
Does anyone have any idea why this happens?

My code

public Workbook build(Planilha planilha) {
    File file = new File(TEMPLATE_PATH);
    if (!file.exists()) {
        Log.error(this, String.format("File %s not exists.", file.getAbsolutePath()));
        throw new NotFoundException("File not exists.");
    }

    Workbook wb = null;
    try (FileInputStream fs = new FileInputStream(file)) {
        wb = new XSSFWorkbook(fs);
        wb = writeMetadatas(planilha, wb);

        Map<String, Integer> header = getHeader(wb);
        Sheet sheet = wb.getSheetAt(0);
        Row row;
        Cell cell;
        for (int i = 0; i <= 10; i++) {
            row = sheet.getRow(i);
            for (int j = 0; j <= 10; j++) {
                cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
                if (cell.getColumnIndex() == 0 && row.getRowNum() == 7) {
                    cell.setCellValue("teste");
                }
            }

        }

    } catch (Exception e) {
        Log.error(this, "Erro: Planilha não existe", e);
        System.err.print("Erro");
    }


    String tmpDir = System.getProperty("java.io.tmpdir");
    File f = FileUtil.file(PATH, System.currentTimeMillis() + ".xlsx");
    try {
        FileOutputStream fout = new FileOutputStream(f);
        wb.write(fout);
        fout.flush();
        fout.close();
    } catch (Exception e) {
        Log.error(this, "Erro ao abrir arquivo p escrever.");
    }
    return wb;
}

**NullPointer happens in cell.setCellValue("teste");

I'm trying to set that cell enter image description here

Upvotes: 0

Views: 4136

Answers (1)

rgettman
rgettman

Reputation: 178243

First, you can test if the row number is a certain number outside of your for loop that loops over the cells in a row. Pull that if outside your j for loop.

It looks like the Cell doesn't exist. row.getCell(j) is returning null.

You can use a MissingCellPolicy to determine whether you want to return a new Cell if the Cell doesn't already exist. The CREATE_NULL_AS_BLANK value will create a blank Cell for you if it doesn't already exist.

Upvotes: 2

Related Questions