前言
主要介绍NPOI(版本2.0.6)的单元格样式CellStyle的设置,具体样式的展现。
1 创建样式
//创建工作簿对象
IWorkbook workBook = new HSSFWorkbook();
//创建样式
ICellStyle cellStyle = workBook.CreateCellStyle();
2 单元格边框
边框样式BorderStyle
一共有14种,具体效果如下
例如设置底部边框为较粗的实线
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
一个单元格有上下左右四个边框可以设置:
//上边框
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thick;
//下边框
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
//左边框
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Dashed;
//右边框
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Double;
每条边框的颜色设置
cellStyle.TopBorderColor = HSSFColor.Blue.Index;
cellStyle.BottomBorderColor = HSSFColor.Yellow.Index;
cellStyle.LeftBorderColor = HSSFColor.Green.Index;
cellStyle.RightBorderColor = HSSFColor.Red.Index;
2 单元格背景颜色
颜色的定义可以查看HSSFColor
类的介绍
//天蓝色
cellStyle.FillForegroundColor = (short)40;
//红色
cellStyle.FillBackgroundColor = (short)10;
//必须设置,否则不起作用
cellStyle.FillPattern = FillPattern.SolidForeground;
效果图:
3 单元格字体
IFont font = cellStyle.GetFont(workBook);
font.FontName = "微软雅黑"; //字体
font.Color = 10; //红色
font.FontHeightInPoints = 16; //字体高度(Excel中的字号)
font.IsItalic = true; //斜体
font.IsStrikeout = true; //删除线
font.Underline = FontUnderlineType.DoubleAccounting; //下划线
cellStyle.SetFont(font);
4 单元格对齐
有水平方向对齐NPOI.SS.UserModel.HorizontalAlignment
还有垂直方向对齐NPOI.SS.UserModel.VerticalAlignment
水平方向 | 垂直方向 | |||
---|---|---|---|---|
Center | 水平居中 | Center | 垂直居中 | |
General | 常规 | Top | 上对齐 | |
Left | 靠左 | Bottom | 底部对齐 | |
Right | 靠右 | Justify | 两端对齐 | |
Fill | 填充 | Distributed | 分散对齐 | |
Justify | 两端对齐 | |||
CenterSelection | 跨列居中 | |||
Distributed | 分散对齐 |
//水平方向对齐 居中对齐
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//垂直方向对齐 底部对齐
cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Bottom;
5 单元格填充图案
NPOI.SS.UserModel.FillPattern
填充图案,为了更好区分图案,下面还使用不同颜色进行标记。
ICellStyle style_0 = workBook.CreateCellStyle();
style_0.FillPattern = NPOI.SS.UserModel.FillPattern.NoFill;
style_0.FillForegroundColor = HSSFColor.BlueGrey.Index;
ICellStyle style_1 = workBook.CreateCellStyle();
style_1.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
style_1.FillForegroundColor = HSSFColor.BlueGrey.Index;
ICellStyle style_2 = workBook.CreateCellStyle();
style_2.FillPattern = NPOI.SS.UserModel.FillPattern.FineDots;
style_2.FillForegroundColor = HSSFColor.Red.Index;