Apache POI 3.17升5.2.2后getFontIndex编译类型转换报错求助
Apache POI 3.17迁移到5.2.2的编译错误解决
问题原因
Apache POI 5.x版本对CellStyle.getFontIndex()的返回值类型做了调整:
- 3.17版本中该方法返回
short类型 - 5.2.2版本中该方法返回
int类型
你原代码里把int类型的返回值直接赋值给short类型变量,就触发了“possible lossy conversion from int to short”的编译错误。
解决方案
方案1:修改变量类型为int(推荐)
直接将fontIndex的类型改为int,因为5.2.2版本的Workbook.getFontAt()已经支持接收int参数,完全适配最新API:
Workbook wb = sheet.getWorkbook(); CellStyle cellStyle = longestTextCell.getCellStyle(); int fontIndex = cellStyle.getFontIndex(); Font excelFont = wb.getFontAt(fontIndex);
方案2:强制类型转换(不推荐)
如果一定要保留short类型,可以添加强制转换,但要注意:若返回的int值超出short的范围(-32768到32767),会导致数值溢出问题:
Workbook wb = sheet.getWorkbook(); CellStyle cellStyle = longestTextCell.getCellStyle(); short fontIndex = (short) cellStyle.getFontIndex(); Font excelFont = wb.getFontAt(fontIndex);
内容的提问来源于stack exchange,提问作者Alexdu98
相关产品推荐
相关产品推荐

