【转】.NET NPOI操作Excel常用函数

最近因项目接触了NPOI,感觉还是蛮不错的,网络上的教程普遍版本较老,本篇记录所常用操作,采用NPOI 2.0版本。

推荐:

新建Excel

HSSFWorkbook hssfworkbook = new HSSFWorkbook ();
ISheet sheet1 = hssfworkbook . CreateSheet ( "sheet1" ); //建立Sheet1

 

保存(导出) Excel
FileStream file = new FileStream (@ "e:\HSSFWorkbook.xls" , FileMode . Create );
hssfworkbook . Write ( file );
file . Close ();

 

导入 Excel
FileStream file = new FileStream (@ "template/Template.xls" , FileMode . Open , FileAccess . Read );
hssfworkbook = new HSSFWorkbook ( file );

 

添加文字
ICell cell1 =HSSFCellUtil.CreateCell(sheet1.CreateRow(0),0,"A1");//添加A1到A1单元,并对Row0实例化
ICell cell2 = HSSFCellUtil.CreateCell(sheet1.GetRow(0), 1, " B1 ");//添加B1到B1单元,此方法需Row0实例化后才可使用
sheet1.GetRow(0).CreateCell(2).SetCellValue("C1");//添加C1到C1单元,此方法需Row0实例化才可使用
sheet1.CreateRow(1).CreateCell(0).SetCellValue("A2");//添加A2到A2单元,并对Row1实例化
 
注意添加文字时候对单元格实例化问题,如果在同一单元格,多次实例化后,会覆盖同行的文字。提供了两种添加文字方式,各有优缺点吧。

 

设置字体格式
IFont font1 = hssfworkbook.CreateFont();
font1.FontName="宋体";//字体
font1.FontHeightInPoints = 20;//字号
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 包含了字体格式、颜色、边框等设置,当设置好 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;

添加边框要对上下左右边框都进行描述。

 

设置对齐相关设置

ICellStyle style3 = hssfworkbook.CreateCellStyle(); style3.Alignment= NPOI.SS.UserModel.HorizontalAlignment.CENTER;//居中 style3.VerticalAlignment=VerticalAlignment.CENTER;//垂直居中 style3.WrapText=true;//自动换行

sheet1.GetRow(0).GetCell(2).CellStyle= style3;

 

转载自:http://anchises.blog.163.com/blog/static/6432108220129211423620/

转载于:https://www.cnblogs.com/xinyuxin912/archive/2013/02/25/2931632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值