很多表格中都要使用边框,本节将为你重点讲解NPOI中边框的设置和使用。
边框和其他单元格设置一样也是调用ICellStyle接口,ICellStyle有2种和边框相关的属性,分别是:
边框相关属性 | 说明 | 范例 |
Border+方向 | 边框类型 | BorderTop, BorderBottom,BorderLeft, BorderRight |
方向+BorderColor | 边框颜色 | TopBorderColor,BottomBorderColor, LeftBorderColor, RightBorderColor |
其中边框类型分为以下几种:
至于颜色那就很多了,全部在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;
这段代码使用了最普通的细边框,使得这个单元格看上去像块空心砖头。
注意:这里我们没有设置边框的颜色,但这不会影响最终的效果,因为Excel会用默认的黑色给边框上色。
如果要设置颜色的话,也很简单,如下:
style.BottomBorderColor= HSSFColor.GREEN.index;
以上代码将底部边框设置为绿色,要注意,不是直接把HSSFColor.GREEN赋给XXXXBorderColor属性,而是把index的值赋给它。