Apache POI CellStyle cloneStyleFrom

問題描述

在使用 Apache POI-3.8的時候,須要一個功能,就是處理上傳得 Excel的 cell style。若是數據有錯誤,則標紅或者加上其餘 style 標識。可是當直接獲取到 cell 的 style 進行處理後,再 set 回去會發現不少其餘的 cell 的 style 也被修改了。實際上是由於在 Excel 中,多個 cell 會共用一個 style,這樣會就沒必要爲每一個 cell存儲一個 style。因此雖然咱們只想修改一個 cell 的 style,其餘 cell 也跟着變了。spa

 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);

解決方法

使用 POI提供的方法 - cloneStyleFrom 來克隆一個 style 出來專門爲這個 cell 來設置 style。code

 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);
相關文章
相關標籤/搜索