I have created an Excel reader using Apache POI. I am able to get the cell value:
cell=sh.getRow(row).getCell(col);
After this, I want to convert the cell object to string as my Excel sheet cell can be of any type, so I am converting it to generic string value. So, I can do it is by just writing:
data[row][col]=cell.toString();
However, I see the practice which is generally followed ie create a new cellToString
method like below:
public String cellToString(HSSFCell cell){
int type;
Object result;
type=cell.getCellType();
switch(type){
case 0:
result=cell.getNumericCellValue();
break;
case 1:
result=cell.getStringCellValue();
break;
default:
throw new RuntimeException("There is no support of this type of cell");
}
return result.toString();
}
And then call the above function like:
data[row][col]=cellToString(cell);
Could someone tell me why we don't follow the first approach directly as it works as well.
I'd wager that most of the time you'd be better off with a wrapper, as in cases where:
you want to ensure that only certain types of cells are processed, throwing on all other types, as the implementer of cellToString()
above obviously wanted to do
you don't care to distinguish between missing and empty cells, and don't want your code sprinkled with checking the return value from getCell()
for null
you're not happy with the default formatting of the cell
.. or any other case when you're not happy to have just any string to chew on. Your mileage will certainly vary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.