You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:57:17