Search code examples
excelapache-poicellxssf

How to set cell type as string in Apache POI XSSF 4.10?


I'm trying to set the cell value as String using Apache POI XSSF 4.10 .

I have used the code

sheet.getRow(i).getCell(k).setCellType(CellType.STRING); but it throws null pointer exception.

Please help


Solution

  • Unless you have already created the cell in your code, always check if it exists. If you only write to each cell once and you only access them once, the code can be much easier.

    Access and write only once (assuming a sheet exists):

    Row r = sheet.createRow(rownum);
    Cell c = r.createCell(column);
    c.setCellType(CellType.STRING);
    

    Full code to access cells multiple times:

    Row r = sheet.getRow(rownum);
    if (r == null) {
        r = sheet.createRow(rownum);
    }
    Cell c = r.getCell(column);
    if (c == null) {
        c = r.createCell(column);
    }
    c.setCellType(CellType.STRING);
    

    Both codes ensure that the cell exists as the getXYZ methods can return NULL if the specified sheet, row, cell have not yet been created.