setCellType(CellType.STRING) is deprecated

Viewed 9872

Issue: setCellType is deprecated.

 row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);

So far tried:

Searched for replacement. No useful sources for setting a cell type as STRING. Appreciate help!

4 Answers

You can just call row.setCellValue(String) you don't have to set the cell type beforehand.

From the docs:

@deprecated This method is deprecated and will be removed in POI 5.0.
     * Use explicit {@link #setCellFormula(String)}, <code>setCellValue(...)</code> or {@link #setBlank()}
     * to get the desired result.

Before:

       row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(                                
       contentValues.put(ITEMCODE, row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue());

After:

InputStream strm =getClass().getResourceAsStream("Sample.xls"));
Workbook wb = WorkbookFactory.create(strm);
DataFormatter Stringform = new DataFormatter();
FormulaEvaluator Formeval = new HSSFFormulaEvaluator((HSSFWorkbook) wb);

Sheet sheet= wb.getSheetAt(0);
Iterator<Row> rit = sheet.rowIterator();

while(rit.hasNext()){

    Row row = rit.next();
    Cell cellValue = row.getCell(0);
    Formeval.evaluate(row.getCell(0)); // Returns string
    String cellValueStr = Stringform.formatCellValue(row.getCell(0),Formeval);
    
    ContentValues contentValues = new ContentValues();

    contentValues.put(DNNO, Stringform.formatCellValue(row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK),Formeval));
                                                                 
}

Instead of directly performing operation on getCell, do get & set operation separately using XSSFCell

XSSFCell cell = (XSSFCell) row.getCell(cellNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.setCellType(CellType.STRING);

2021 UPDATE still no solution, so to achieve this (for example, set cell type to Decimal), you could use this code:

double someValue = 50.0;
CellStyle styleDecimal = workbook.createCellStyle();
styleDecimal.setDataFormat(workbook.createDataFormat().getFormat("0.00"));
row.getCell(0).setCellStyle(styleDecimal);
try{
    Double.valueOf(someValue);
    row.getCell(0).setCellValue(Double.valueOf(someValue));
}catch (Exception ex){}
Related