NPOI 第二篇 设置样式与合并单元格(转)

前言

上一篇NPOI的文章介绍了NPOI的下载、引用以及基本使用方法。本文将进一步讲解NPOI,给出了设置单元格样式以及合并单元格的代码示例。

上一篇博客《NPOI的下载、引用、基本使用》链接:

https://blog.csdn.net/wf824284257/article/details/77113691

开始

本文将通过一个简单的例子来讲解NPOI的单元格样式及合并单元格的方法。

所使用的测试数据如图:

上图为 sql server 数据库中的表数据。在实际应用场景中,数据往往是通过查询数据库(DB)来获取的,但本文为了方便读者下载示例代码,该表数据将直接写死在代码里。本文示例代码项目可以从博主资源页下载,下载地址为:

https://download.csdn.net/download/wf824284257/10899002

我们需要将该表数据导出为excel文件下载,目标excel格式如下:

下面将分步骤讲解如何做到这样的效果。

Step1. 表头单元格样式

表头样式设置水平居中、大小14、黄背景红字、红底线。参考代码如下:

//表头样式
ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.Boldweight = 20;
font.FontHeightInPoints = 14;
font.Color = HSSFColor.Red.Index;
headStyle.SetFont(font);
//以下三行为背景色
headStyle.FillForegroundColor = HSSFColor.Yellow.Index;
headStyle.FillPattern = FillPattern.Squares;
headStyle.FillBackgroundColor = HSSFColor.Yellow.Index;
//border
headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
headStyle.BottomBorderColor = HSSFColor.Red.Index;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Step2. 普通单元格样式

普通单元格样式设置水平居中、垂直居中、绿字。参考代码如下:

//普通单元格样式
ICellStyle bodyStyle = workbook.CreateCellStyle();
bodyStyle.Alignment = HorizontalAlignment.Center;
bodyStyle.VerticalAlignment = VerticalAlignment.Center;
IFont font1 = workbook.CreateFont();
font1.Color = HSSFColor.Green.Index;
font1.Boldweight = 20;
bodyStyle.SetFont(font1);
1
2
3
4
5
6
7
8
Step3. 合并行

合并行使用 ISheet.AddMergedRegion 方法来实现。对于本文示例,可以从第0列即id列入手,在对sheet的行进行遍历的基础上,对于具有相同id的行的前两列进行纵向合并。

参考代码如下:

//合并行
for(int i = 1; i < dt.Rows.Count + 1; i++)
{
string value = sheet.GetRow(i).GetCell(0).StringCellValue;
int end = i;
//找到结束为止
for(int j = i + 1; j < dt.Rows.Count + 1; j++)
{
string value1= sheet.GetRow(j).GetCell(0).StringCellValue;
if (value != value1)
{
end = j - 1;
break;
}
else if(value==value1 && j == dt.Rows.Count)
{
end = j;
break;
}
}
sheet.AddMergedRegion(new CellRangeAddress(i, end, 0, 0));
sheet.AddMergedRegion(new CellRangeAddress(i, end, 1, 1));
i = end;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Step4. 设置列宽

参考代码如下:

//列宽
sheet.SetColumnWidth(0, 20 * 256);
sheet.SetColumnWidth(1, 20 * 256);
sheet.SetColumnWidth(2, 20 * 256);
sheet.SetColumnWidth(3, 20 * 256);
1
2
3
4
5
至此,该excel的格式设置完毕。

结束

本文将通过一个简单的例子讲解了NPOI的单元格样式设置及单元格合并的方法。该示例代码项目目录如下图所示:

该项目可以在博主资源页下载:

https://download.csdn.net/download/wf824284257/10899002
————————————————
版权声明:本文为CSDN博主「Fanstorm丶」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wf824284257/article/details/85920867

原文地址:https://www.cnblogs.com/xihong2014/p/14660171.html