NPOI 設置單元格邊框


很多表格中都要使用邊框,本節將為你重點講解NPOI中邊框的設置和使用。

邊框和其他單元格設置一樣也是調用ICellStyle接口,ICellStyle有2種和邊框相關的屬性,分別是:

邊框相關屬性 說明 范例
Border+方向 邊框類型 BorderTop, BorderBottom,BorderLeft, BorderRight
方向+BorderColor 邊框顏色 TopBorderColor,BottomBorderColor, LeftBorderColor, RightBorderColor

其中邊框類型分為以下幾種:

邊框范例圖 對應的靜態值
image CellBorderType.DOTTED
image CellBorderType.HAIR
image CellBorderType.DASH_DOT_DOT
image CellBorderType.DASH_DOT
image CellBorderType.DASHED
image CellBorderType.THIN
image CellBorderType.MEDIUM_DASH_DOT_DOT
image CellBorderType.SLANTED_DASH_DOT
image CellBorderType.MEDIUM_DASH_DOT
image CellBorderType.MEDIUM_DASHED
image CellBorderType.MEDIUM
image CellBorderType.THICK
image CellBorderType.DOUBLE

至於顏色那就很多了,全部在HSSFColor下面,如HSSFColor.GREEN, HSSFColor.RED,都是靜態實例,可以直接引用。

下面我們假設我們要把一個單元格的四周邊框都設置上,可以用下面的代碼:

ISheet sheet = hssfworkbook.CreateSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
IRow row = sheet.CreateRow(1);
// Create a cell and put a value in it.
ICell cell = row.CreateCell(1);
// Style the cell with borders all around.
ICellStyle style = hssfworkbook.CreateCellStyle();
style.BorderBottom= CellBorderType.THIN;
style.BorderLeft= CellBorderType.THIN;
style.BorderRight= CellBorderType.THIN;
style.BorderTop = CellBorderType.THIN;
cell.CellStyle= style;


這段代碼使用了最普通的細邊框,使得這個單元格看上去像塊空心磚頭。

image

注意:這里我們沒有設置邊框的顏色,但這不會影響最終的效果,因為Excel會用默認的黑色給邊框上色。

如果要設置顏色的話,也很簡單,如下:

 
style.BottomBorderColor= HSSFColor.GREEN.index;

以上代碼將底部邊框設置為綠色,要注意,不是直接把HSSFColor.GREEN賦給XXXXBorderColor屬性,而是把index的值賦給它。


免責聲明!

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



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