java rowstyle_POI CellStyle 中样式覆盖问题

在使用 Apache POI-3.8的时候,需要一个功能,就是处理上传得 Excel的 cell style。如果数据有错误,则标红或者加上其他 style 标识。但是当直接获取到 cell 的 style 进行处理后,再 set 回去会发现很多其他的 cell 的 style 也被修改了。其实是因为在 Excel 中,多个 cell 会共用一个 style,这样会就不必为每个 cell存储一个 style。所以虽然我们只想修改一个 cell 的 style,其他 cell 也跟着变了。

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 // 改一个style,其他的cell 的 style也跟着变了

2 Cell cell = row.getCell(cellIndex);

3

4 CellStyle style = cell.getRow().getSheet().getWorkbook().createCellStyle();

5

6 style.setBorderBottom(CellStyle.BORDER_THIN);

7 style.setBorderLeft(CellStyle.BORDER_THIN);

8 style.setBorderRight(CellStyle.BORDER_THIN);

9 style.setBorderTop(CellStyle.BORDER_THIN);

10 style.setBottomBorderColor(IndexedColors.RED.index);

11 style.setLeftBorderColor(IndexedColors.RED.index);

12 style.setRightBorderColor(IndexedColors.RED.index);

13 style.setTopBorderColor(IndexedColors.RED.index);

14

15 cell.setCellStyle(style);

48304ba5e6f9fe08f3fa1abda7d326ab.png

解决方法

使用 POI提供的方法 - cloneStyleFrom 来克隆一个 style 出来专门为这个 cell 来设置 style。

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 Cell cell = row.getCell(cellIndex);

2

3 CellStyle style = cell.getRow().getSheet().getWorkbook().createCellStyle();

4 style.cloneStyleFrom(cell.getCellStyle()); // 克隆出一个 style

5

6 style.setBorderBottom(CellStyle.BORDER_THIN);

7 style.setBorderLeft(CellStyle.BORDER_THIN);

8 style.setBorderRight(CellStyle.BORDER_THIN);

9 style.setBorderTop(CellStyle.BORDER_THIN);

10 style.setBottomBorderColor(IndexedColors.RED.index);

11 style.setLeftBorderColor(IndexedColors.RED.index);

12 style.setRightBorderColor(IndexedColors.RED.index);

13 style.setTopBorderColor(IndexedColors.RED.index);

14

15 cell.setCellStyle(style);

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值