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 也跟着變了。

 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。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM