NPOI操作Excel(二)--创建Excel并设置样式

由于XSSF中的XSSFWorkbook和HSSF中的HSSFWorkbook拥有的属性、方法等都是一样的,故下面就已一个为例做为展示,他们都继承与一个接口:IWorkbook(命名空间:using NPOI.SS.UserModel;)

1、创建工作簿

1 IWorkbook myHSSFworkbook = new HSSFWorkbook();  //用于创建 .xls
2 IWorkbook myXSSFworkbook = new XSSFWorkbook();  //用于创建 .xlsx

2、按指定名称创建Sheet

ISheet mysheetHSSF = myHSSFworkbook.CreateSheet("SheetName");

3、创建Sheet中的Row

IRow rowHSSF = mysheetHSSF.CreateRow(0);

4、创建Row中的列Cell并赋值【SetCellValue有5个重载方法 bool、DateTime、double、string、IRichTextString(未演示)】

1 rowHSSF.CreateCell(0).SetCellValue(true);
2 rowHSSF.CreateCell(1).SetCellValue(System.DateTime.Now);
3 rowHSSF.CreateCell(2).SetCellValue(10.13);
4 rowHSSF.CreateCell(3).SetCellValue("学习NPOI");

 5、合并单元格【CellRangeAddress(开始行,结束行,开始列,结束列)】

mysheetHSSF=.AddMergedRegion(new CellRangeAddress(1, 1, 1, 2)); //合并单元格第二行从第二列到第三列
IRow SecondRowHSSF = mysheetHSSF.CreateRow(1); //添加第二行
SecondRowHSSF.CreateCell(0).SetCellValue("第一列"); 
SecondRowHSSF.CreateCell(1).SetCellValue("第二列到第三列"); 
SecondRowHSSF.CreateCell(3).SetCellValue("第四列"); 

6、设置列宽【SetColumnWidth(列索引,N*256) 第二个参数是列宽 单位是1/256个字符宽度】

 mysheetHSSF.SetColumnWidth(3, 30 * 256); //设置第四列的列宽为30个字符 

7、设置行高【Height的单位是1/20个点】

 SecondRowHSSF.Height=50*20; //设置高度为50个点 

8、设置单元格对齐方式 

 1 IRow ThirdRowHSSF = mysheetHSSF.CreateRow(2);
 2 ThirdRowHSSF.Height = 50 * 20;
 3 ThirdRowHSSF.CreateCell(0).SetCellValue("默认对齐");
 4 ThirdRowHSSF.CreateCell(1).SetCellValue("左对齐");
 5 ThirdRowHSSF.CreateCell(2).SetCellValue("居中");
 6 ThirdRowHSSF.CreateCell(3).SetCellValue("右对齐");
 7 IRow FourthRowHSSF = mysheetHSSF.CreateRow(3);
 8 FourthRowHSSF.Height = 50 * 20;
 9 FourthRowHSSF.CreateCell(0).SetCellValue("填充单元格");
10 FourthRowHSSF.CreateCell(1).SetCellValue("she zhi dan yuan ge liang duan dui qi");
11 FourthRowHSSF.CreateCell(2).SetCellValue("跨列居中");
12 FourthRowHSSF.CreateCell(3).SetCellValue("分散对齐");
13 
14 //创建CellStyle  
15 ICellStyle style0 = myHSSFworkbook.CreateCellStyle();
16 style0.Alignment = HorizontalAlignment.General;//【General】数字、时间默认:右对齐;BOOL:默认居中;字符串:默认左对齐  
17 
18 ICellStyle style1 = myHSSFworkbook.CreateCellStyle();
19 style1.Alignment = HorizontalAlignment.Left;//【Left】左对齐  
20 
21 ICellStyle style2 = myHSSFworkbook.CreateCellStyle();
22 style2.Alignment = HorizontalAlignment.Center;//【Center】居中  
23 
24 ICellStyle style3 = myHSSFworkbook.CreateCellStyle();
25 style3.Alignment = HorizontalAlignment.Right;//【Right】右对齐  
26 
27 ICellStyle style4 = myHSSFworkbook.CreateCellStyle();
28 style4.Alignment = HorizontalAlignment.Fill;//【Fill】填充  
29 
30 ICellStyle style5 = myHSSFworkbook.CreateCellStyle();
31 style5.Alignment = HorizontalAlignment.Justify;//【Justify】两端对齐[会自动换行](主要针对英文)  
32 ICellStyle style6 = myHSSFworkbook.CreateCellStyle();
33 style6.Alignment = HorizontalAlignment.CenterSelection;//【CenterSelection】跨列居中  
34 
35 ICellStyle style7 = myHSSFworkbook.CreateCellStyle();
36 style7.Alignment = HorizontalAlignment.Distributed;//【Distributed】分散对齐[会自动换行]
37 
38 //【Tips】  
39 // 1.通过ICellStyle的VerticalAlignment属性可以设置垂直对齐模式与水平对齐无异 不再演示  
40 // 2.通过ISheet的SetDefaultColumnStyle(int column, ICellStyle style)方法可以设置整列的默认单元格样式; 
41 
42 //将CellStyle应用于具体单元格  
43 ThirdRowHSSF.GetCell(0).CellStyle = style0;
44 ThirdRowHSSF.GetCell(1).CellStyle = style1;
45 ThirdRowHSSF.GetCell(2).CellStyle = style2;
46 ThirdRowHSSF.GetCell(3).CellStyle = style3;
47 
48 FourthRowHSSF.GetCell(0).CellStyle = style4;
49 FourthRowHSSF.GetCell(1).CellStyle = style5;
50 FourthRowHSSF.GetCell(2).CellStyle = style6;
51 FourthRowHSSF.GetCell(3).CellStyle = style7;
View Code

9、设置单元格背景与图案【Pattern的填充图案没有演示全,下面的图片是效果图】

 1 IRow FifthRowHSSF = mysheetHSSF.CreateRow(4);
 2 FifthRowHSSF.CreateCell(0).SetCellValue("NoFill"); 
 3 FifthRowHSSF.CreateCell(1).SetCellValue("SolidForeground"); 
 4 FifthRowHSSF.CreateCell(2).SetCellValue("FineDots"); 
 5 FifthRowHSSF.CreateCell(3).SetCellValue("AltBars"); 
 6 
 7 //【Tips】  
 8 // 1.ForegroundColor(默认黑色)【前景颜色】BackgroundColor(默认为前景颜色的反色)【背景颜色】Pattern(必须指定,默认NoFill)【填充的图案】  
 9 // 2.演示中使用 【前景颜色】蓝色 【背景颜色】白色  
10 
11 //创建CellStyle并应用于单元格    
12 ICellStyle Blackstyle0 = myHSSFworkbook.CreateCellStyle(); Blackstyle0.FillBackgroundColor = IndexedColors.White.Index;
13 Blackstyle0.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle0.FillPattern = FillPattern.NoFill;
14 FifthRowHSSF .GetCell(0).CellStyle = Blackstyle0;
15 ICellStyle Blackstyle1 = myHSSFworkbook.CreateCellStyle(); Blackstyle1.FillBackgroundColor = IndexedColors.White.Index;
16 Blackstyle1.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle1.FillPattern = FillPattern.SolidForeground;
17 FifthRowHSSF .GetCell(1).CellStyle = Blackstyle1;
18 ICellStyle Blackstyle2 = myHSSFworkbook.CreateCellStyle(); Blackstyle2.FillBackgroundColor = IndexedColors.White.Index;
19 Blackstyle2.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle2.FillPattern = FillPattern.FineDots;
20 FifthRowHSSF .GetCell(2).CellStyle = Blackstyle2;
21 ICellStyle Blackstyle3 = myHSSFworkbook.CreateCellStyle(); Blackstyle3.FillBackgroundColor = IndexedColors.White.Index;
22 Blackstyle3.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle3.FillPattern = FillPattern.AltBars;
23 FifthRowHSSF .GetCell(3).CellStyle = Blackstyle3;
View Code

 10、设置单元格边框

 1 ICellStyle BorderStyle = myworkbook.CreateCellStyle(); BorderStyle .BorderBottom = BorderStyle.Thin;//设置单元格低边框为细线
 2 //BorderStyle.Medium;【中等线】
 3 //BorderStyle.Dashed;【虚线】
 4 //BorderStyle.Dotted;【斑点线】
 5 //BorderStyle.Thick;【粗线】
 6 //BorderStyle.Double;【双线】
 7 //BorderStyle.Hair;【多点线】
 8 //BorderStyle.MediumDashed;【中等虚线】
 9 //BorderStyle.DashDot;【点线】
10 //BorderStyle.MediumDashDot;【中等点线】
11 //BorderStyle.DashDotDot;【双点划线】
12 //BorderStyle.MediumDashDotDot;【中等双点划线】
13 //BorderStyle.SlantedDashDot;【倾斜的点划线】
14 ICellStyle BorderStyle1 = myworkbook.CreateCellStyle(); 
15 BorderStyle1.BorderDiagonalLineStyle = BorderStyle.Thin;//BorderDiagonalLineStyle对角线样式 Thin细线
16 BorderStyle1.BorderDiagonal = BorderDiagonal.Backward;//反向【Forward正向;Both两条线】
17 BorderStyle1.BorderDiagonalColor = IndexedColors.Red.Index;//红线
View Code

 11、设置Excel字体

 1 //设置字体样式  
 2 IFont font = myworkbook.CreateFont();
 3 font.Boldweight = (Int16)FontBoldWeight.Bold;//原始字体
 4 //【Tips】  
 5 // 1.Boldweight 要使用(Int16)FontBoldWeight 对应的数值 否则无效
 6 font=.Color = IndexedColors.Red.Index; //设置字体颜色
 7 font.FontHeight = 17;//设置字体高度【FontHeightInPoints也是设置字体高度,我还不知道有啥区别】
 8 font.FontName = "黑体";//设置字体
 9 font.IsBold = true;//是否加粗
10 font.IsItalic = true;//是否斜体
11 font.IsStrikeout = true;//是否加删除线
12 font.TypeOffset = FontSuperScript.Sub;//设置脚本上的字体【Sub 下;Super 上】
13 font.Underline = FontUnderlineType.Single;//下划线【Single一条线;Double两条线】
14 //创建CellStyle并加载字体
15 ICellStyle Fontstyle = myHSSFworkbook.CreateCellStyle();
16 Fontstyle.SetFont(font);
View Code

12、设置单元格数字格式

 1 //创建CellStyle与DataFormat并加载格式样式  
 2 IDataFormat dataformat = myworkbook.CreateDataFormat();
 3 ICellStyle Numstyle = myworkbook.CreateCellStyle();
 4 Numstyle.DataFormat = dataformat.GetFormat("[DbNum2][$-804]General");//转化为汉字大写
 5 // dataformat.GetFormat("0.0"); //改变小数精度【小数点后有几个0表示精确到小数点后几位】 
 6 //dataformat.GetFormat("#,##0.0");//分段添加,号
 7 //dataformat.GetFormat("0.00E+00");//科学计数法
 8 //dataformat.GetFormat("0.00;[Red]-0.00");//正数与负数的区分【负数为红色】
 9 //dataformat.GetFormat("# ??/??");//整数部分+分数
10 //dataformat.GetFormat("??/??");//分数
11 //dataformat.GetFormat("0.00%");//百分数【小数点后有几个0表示精确到显示小数点后几位】 
View Code

13、设置单元格时间格式 

 1 //创建CellStyle与DataFormat并加载格式样式  
 2 IDataFormat dataformat = myworkbook.CreateDataFormat();
 3 //【Tips】  
 4 // 1.yyyy 年份;    yy 年份后两位  
 5 // 2.MM 月份零起始;M 月份非零起始;  mmm[英文月份简写];mmmm[英文月份全称]  
 6 // 3.dd   日零起始;d 日非零起始  
 7 // 4.hh 小时零起始;h 小时非零起始[用于12小时制][12小时制必须在时间后面添加 AM/PM 或 上午/下午]  
 8 // 5.HH 小时零起始;H 小时非零起始[用于24小时制]  
 9 // 6.mm 分钟零起始;m 分钟非零起始  
10 // 7.ss 秒数零起始;s 秒数非零起始  
11 // 8.dddd 星期;ddd 星期缩写【英文】  
12 // 9.aaaa 星期;aaa 星期缩写【中文】 
13 ICellStyle Timestyle = myworkbook.CreateCellStyle();
14 Timestyle.DataFormat = dataformat.GetFormat("yyyy年MM月dd日 aaaa");【2017年09月01日 星期五】
15 //dataformat.GetFormat("yyyy年MM月dd日 dddd");【2017年09月01年 Friday】
16 //dataformat.GetFormat("h:mm:ss AM/PM");【3:51:21 PM】
17 //dataformat.GetFormat("h:mm:ss 上午/下午");【3:51:21 下午】
View Code

14、设置单元格文本格式

1 IDataFormat dataformat = myworkbook.CreateDataFormat();
2 
3 //【Tips】   使用@ 或 text 都可以
4 ICellStyle Textstyle = myworkbook.CreateCellStyle(); Textstyle.DataFormat = dataformat.GetFormat("@");
5 //dataformat.GetFormat("text");
View Code

15、插入图片 

 1 //第一步:读取图片到byte数组  
 2 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://img1.soufunimg.com/message/images/card/tuanproj/201511/2015112703584458_s.jpg");
 3 byte[] bytes;
 4 using (Stream stream = request.GetResponse().GetResponseStream())
 5             {
 6                 using (MemoryStream mstream = new MemoryStream())
 7                 {
 8                     int count = 0;
 9                     byte[] buffer = new byte[1024];
10                     int readNum = 0;
11                     while ((readNum = stream.Read(buffer, 0, 1024)) > 0)
12                     {
13                         count = count + readNum;
14                         mstream.Write(buffer, 0, 1024);
15                     }
16                     mstream.Position = 0;
17                     using (BinaryReader br = new BinaryReader(mstream))
18                     {
19 
20                         bytes = br.ReadBytes(count);
21                     }
22                 }
23             }
24 
25 //第二步:将图片添加到workbook中  指定图片格式 返回图片所在workbook->Picture数组中的索引地址(从1开始)  
26 int pictureIdx = myworkbook.AddPicture(bytes, PictureType.JPEG);
27 
28 //第三步:在sheet中创建画部  
29 IDrawing patriarch = mysheet.CreateDrawingPatriarch();
30 //第四步:设置锚点 (在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)  
31 IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, 0, 0, 2, 2);
32 //第五步:创建图片  
33 IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
View Code

16、保存Excel

FileStream file = new FileStream(@"D:\CreateExcel.xls", FileMode.Create);
myworkbook.Write(file);
file.Close();

 参考:http://blog.csdn.net/xxs77ch/article/details/50174609

posted @ 2017-09-01 17:55  念宇儿  阅读(14196)  评论(2编辑  收藏  举报