NPOI操作Excel之二創(chuàng)建Excel并設(shè)置樣式
由于XSSF中的XSSFWorkbook和HSSF中的HSSFWorkbook擁有的屬性、方法等都是一樣的,故下面就已一個為例做為展示,他們都繼承與一個接口:IWorkbook(命名空間:using NPOI.SS.UserModel;)
1、創(chuàng)建工作簿
- IWorkbook myHSSFworkbook = new HSSFWorkbook(); //用于創(chuàng)建 .xls
- IWorkbook myXSSFworkbook = new XSSFWorkbook(); //用于創(chuàng)建 .xlsx
2、按指定名稱創(chuàng)建Sheet
- ISheet mysheetHSSF = myHSSFworkbook.CreateSheet("SheetName");
3、創(chuàng)建Sheet中的Row
- IRow rowHSSF = mysheetHSSF.CreateRow(0);
4、創(chuàng)建Row中的列Cell并賦值【SetCellValue有5個重載方法 bool、DateTime、double、string、IRichTextString(未演示)】
- rowHSSF.CreateCell(0).SetCellValue(true);
- rowHSSF.CreateCell(1).SetCellValue(System.DateTime.Now);
- rowHSSF.CreateCell(2).SetCellValue(10.13);
- rowHSSF.CreateCell(3).SetCellValue("學(xué)習(xí)NPOI!");
5、合并單元格【CellRangeAddress(開始行,結(jié)束行,開始列,結(jié)束列)】
- 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、設(shè)置列寬【SetColumnWidth(列索引,N*256) 第二個參數(shù)是列寬 單位是1/256個字符寬度】
- mysheetHSSF.SetColumnWidth(3, 30 * 256); //設(shè)置第四列的列寬為30個字符
7、設(shè)置行高【Height的單位是1/20個點】
- SecondRowHSSF.Height=50*20; //設(shè)置高度為50個點
8、設(shè)置單元格對齊方式
- 1 IRow ThirdRowHSSF = mysheetHSSF.CreateRow(2);
- 2 ThirdRowHSSF.Height = 50 * 20;
- 3 ThirdRowHSSF.CreateCell(0).SetCellValue("默認(rèn)對齊");
- 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 //創(chuàng)建CellStyle
- 15 ICellStyle style0 = myHSSFworkbook.CreateCellStyle();
- 16 style0.Alignment = HorizontalAlignment.General;//【General】數(shù)字、時間默認(rèn):右對齊;BOOL:默認(rèn)居中;字符串:默認(rèn)左對齊
- 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屬性可以設(shè)置垂直對齊模式與水平對齊無異 不再演示
- 40 // 2.通過ISheet的SetDefaultColumnStyle(int column, ICellStyle style)方法可以設(shè)置整列的默認(rèn)單元格樣式;
- 41
- 42 //將CellStyle應(yīng)用于具體單元格
- 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;
9、設(shè)置單元格背景與圖案【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(默認(rèn)黑色)【前景顏色】BackgroundColor(默認(rèn)為前景顏色的反色)【背景顏色】Pattern(必須指定,默認(rèn)NoFill)【填充的圖案】
- 9 // 2.演示中使用 【前景顏色】藍(lán)色 【背景顏色】白色
- 10
- 11 //創(chuàng)建CellStyle并應(yīng)用于單元格
- 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;
10、設(shè)置單元格邊框
- 1 ICellStyle BorderStyle = myworkbook.CreateCellStyle(); BorderStyle .BorderBottom = BorderStyle.Thin;//設(shè)置單元格低邊框為細(xì)線
- 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細(xì)線
- 16 BorderStyle1.BorderDiagonal = BorderDiagonal.Backward;//反向【Forward正向;Both兩條線】
- 17 BorderStyle1.BorderDiagonalColor = IndexedColors.Red.Index;//紅線
11、設(shè)置Excel字體
- 1 //設(shè)置字體樣式
- 2 IFont font = myworkbook.CreateFont();
- 3 font.Boldweight = (Int16)FontBoldWeight.Bold;//原始字體
- 4 //【Tips】
- 5 // 1.Boldweight 要使用(Int16)FontBoldWeight 對應(yīng)的數(shù)值 否則無效
- 6 font=.Color = IndexedColors.Red.Index; //設(shè)置字體顏色
- 7 font.FontHeight = 17;//設(shè)置字體高度【FontHeightInPoints也是設(shè)置字體高度,我還不知道有啥區(qū)別】
- 8 font.FontName = "黑體";//設(shè)置字體
- 9 font.IsBold = true;//是否加粗
- 10 font.IsItalic = true;//是否斜體
- 11 font.IsStrikeout = true;//是否加刪除線
- 12 font.TypeOffset = FontSuperScript.Sub;//設(shè)置腳本上的字體【Sub 下;Super 上】
- 13 font.Underline = FontUnderlineType.Single;//下劃線【Single一條線;Double兩條線】
- 14 //創(chuàng)建CellStyle并加載字體
- 15 ICellStyle Fontstyle = myHSSFworkbook.CreateCellStyle();
- 16 Fontstyle.SetFont(font);
12、設(shè)置單元格數(shù)字格式
- 1 //創(chuàng)建CellStyle與DataFormat并加載格式樣式
- 2 IDataFormat dataformat = myworkbook.CreateDataFormat();
- 3 ICellStyle Numstyle = myworkbook.CreateCellStyle();
- 4 Numstyle.DataFormat = dataformat.GetFormat("[DbNum2][$-804]General");//轉(zhuǎn)化為漢字大寫
- 5 // dataformat.GetFormat("0.0"); //改變小數(shù)精度【小數(shù)點后有幾個0表示精確到小數(shù)點后幾位】
- 6 //dataformat.GetFormat("#,##0.0");//分段添加,號
- 7 //dataformat.GetFormat("0.00E+00");//科學(xué)計數(shù)法
- 8 //dataformat.GetFormat("0.00;[Red]-0.00");//正數(shù)與負(fù)數(shù)的區(qū)分【負(fù)數(shù)為紅色】
- 9 //dataformat.GetFormat("# ??/??");//整數(shù)部分+分?jǐn)?shù)
- 10 //dataformat.GetFormat("??/??");//分?jǐn)?shù)
- 11 //dataformat.GetFormat("0.00%");//百分?jǐn)?shù)【小數(shù)點后有幾個0表示精確到顯示小數(shù)點后幾位】
13、設(shè)置單元格時間格式
- 1 //創(chuàng)建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 秒數(shù)零起始;s 秒數(shù)非零起始
- 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 下午】
14、設(shè)置單元格文本格式
- 1 IDataFormat dataformat = myworkbook.CreateDataFormat();
- 2
- 3 //【Tips】 使用@ 或 text 都可以
- 4 ICellStyle Textstyle = myworkbook.CreateCellStyle(); Textstyle.DataFormat = dataformat.GetFormat("@");
- 5 //dataformat.GetFormat("text");
15、插入圖片
- 1 //第一步:讀取圖片到byte數(shù)組
- 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數(shù)組中的索引地址(從1開始)
- 26 int pictureIdx = myworkbook.AddPicture(bytes, PictureType.JPEG);
- 27
- 28 //第三步:在sheet中創(chuàng)建畫部
- 29 IDrawing patriarch = mysheet.CreateDrawingPatriarch();
- 30 //第四步:設(shè)置錨點 (在起始單元格的X坐標(biāo)0-1023,Y的坐標(biāo)0-255,在終止單元格的X坐標(biāo)0-1023,Y的坐標(biāo)0-255,起始單元格行數(shù),列數(shù),終止單元格行數(shù),列數(shù))
- 31 IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, 0, 0, 2, 2);
- 32 //第五步:創(chuàng)建圖片
- 33 IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
16、保存Excel
- FileStream file = new FileStream(@"D:\CreateExcel.xls", FileMode.Create);
- myworkbook.Write(file);
- file.Close();
參考:http://blog.csdn.net/xxs77ch/article/details/50174609
https://www.cnblogs.com/zqyw/category/1070314.html
本文轉(zhuǎn)載自微信公眾號「CSharp編程大全」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系CSharp編程大全公眾號。