【转】.NET NPOI操作Excel常用函数
最近因項(xiàng)目接觸了NPOI,感覺還是蠻不錯(cuò)的,網(wǎng)絡(luò)上的教程普遍版本較老,本篇記錄所常用操作,采用NPOI 2.0版本。
推薦: NPOI官方網(wǎng)站 NPOI 1.2.4/1.2.5 官方教程新建Excel
HSSFWorkbook hssfworkbook =newHSSFWorkbook(); ISheet sheet1 = hssfworkbook.CreateSheet("sheet1");//建立Sheet1?
保存(導(dǎo)出)Excel FileStream file =newFileStream(@"e:\HSSFWorkbook.xls",FileMode.Create); hssfworkbook.Write(file); file.Close();?
導(dǎo)入Excel FileStream file =newFileStream(@"template/Template.xls",FileMode.Open,FileAccess.Read); hssfworkbook =newHSSFWorkbook(file);?
添加文字 ICell cell1 =HSSFCellUtil.CreateCell(sheet1.CreateRow(0),0,"A1");//添加A1到A1單元,并對(duì)Row0實(shí)例化 ICell cell2 = HSSFCellUtil.CreateCell(sheet1.GetRow(0), 1, " B1 ");//添加B1到B1單元,此方法需Row0實(shí)例化后才可使用 sheet1.GetRow(0).CreateCell(2).SetCellValue("C1");//添加C1到C1單元,此方法需Row0實(shí)例化才可使用 sheet1.CreateRow(1).CreateCell(0).SetCellValue("A2");//添加A2到A2單元,并對(duì)Row1實(shí)例化 ? 注意添加文字時(shí)候?qū)卧駥?shí)例化問題,如果在同一單元格,多次實(shí)例化后,會(huì)覆蓋同行的文字。提供了兩種添加文字方式,各有優(yōu)缺點(diǎn)吧。?
設(shè)置字體格式 IFont font1 = hssfworkbook.CreateFont(); font1.FontName="宋體";//字體 font1.FontHeightInPoints = 20;//字號(hào) font1.Color = HSSFColor.RED.index;//顏色 font1.Boldweight = 700;//粗體 font1.IsItalic = true;//斜體 font1.Underline = (byte)FontUnderlineType.DOUBLE;//添加雙下劃線 ICellStyle style1 = hssfworkbook.CreateCellStyle(); style1.SetFont(font1); 字體格式綁定在Style中,Style包含了字體格式、顏色、邊框等設(shè)置,當(dāng)設(shè)置好Style后,賦值給單元格即可。 cell1.CellStyle= style1; sheet1.GetRow(1).GetCell(0).CellStyle= style1;?
合并單元格
sheet1.AddMergedRegion(newCellRangeAddress(2,3,0,1));//合并A3-B4
//CellRangeAddress(起始行,終止行,起始列,終止列);
?
添加邊框
ICellStyle style2 = hssfworkbook.CreateCellStyle(); style2.BorderBottom= NPOI.SS.UserModel.BorderStyle.THIN; style2.BorderLeft= NPOI.SS.UserModel.BorderStyle.THIN; style2.BorderRight= NPOI.SS.UserModel.BorderStyle.THIN; style2.BorderTop= NPOI.SS.UserModel.BorderStyle.THIN;
?
//添加斜線
style2.BorderDiagonal = BorderDiagonal.BACKWARD; style2.BorderDiagonalLineStyle= NPOI.SS.UserModel.BorderStyle.THIN;
cell2.CellStyle= style2;
添加邊框要對(duì)上下左右邊框都進(jìn)行描述。
?
設(shè)置對(duì)齊相關(guān)設(shè)置
ICellStyle style3 = hssfworkbook.CreateCellStyle(); style3.Alignment= NPOI.SS.UserModel.HorizontalAlignment.CENTER;//居中 style3.VerticalAlignment=VerticalAlignment.CENTER;//垂直居中 style3.WrapText=true;//自動(dòng)換行
sheet1.GetRow(0).GetCell(2).CellStyle= style3;
?
轉(zhuǎn)載自:http://anchises.blog.163.com/blog/static/6432108220129211423620/
轉(zhuǎn)載于:https://www.cnblogs.com/xinyuxin912/archive/2013/02/25/2931632.html
總結(jié)
以上是生活随笔為你收集整理的【转】.NET NPOI操作Excel常用函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 训练GAN的技巧
- 下一篇: asp.net ajax控件工具集 Au