npoi获取合并单元格_梦琪小生 C# 如何使用NPOI操作Excel以及读取合并单元格等

本文介绍了如何使用C#的NPOI库进行Excel操作,包括创建、保存数据、设置批注、单元格样式、合并单元格、读取Excel为DataTable等,并提醒了在处理大量数据时,某些功能可能会影响性能。
摘要由CSDN通过智能技术生成

C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office。所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单元格等都能实现。

命名空间:

using NPOI;

using NPOI.XSSF.UserModel;

using NPOI.SS.UserModel;

using NPOI.HSSF.UserModel;

using NPOI.HSSF.Util;

简单的保存数据:

public void ExcelTest(string path)

{

IWorkbook workbook = new HSSFWorkbook();//创建Workbook

workbook.CreateSheet("sheet1");//创建sheet

using (FileStream fs = File.Create(path))//path=mmm.xls;

{

ISheet sheet = workbook.GetSheetAt(0);//获取sheet

sheet.CreateRow(1).CreateCell(0).SetCellValue("nami");//创建第一行/创建第一单元格/设置第一单元格的内容[可以分开创建,但必须先创建行才能创建单元格不然报错]

sheet.GetRow(1).CreateCell(1).SetCellValue("robin");//获取第一行/创建第二单元格/设置第二单元格的内容

sheet.CreateRow(2).CreateCell(0).SetCellValue("saber");//创建第二行/创建第一单元格/设置第一单元格的内容

sheet.GetRow(2).CreateCell(1).SetCellValue("luffy");//获取第二行/创建第二单元格/设置第二单元格的内容

sheet.GetRow(1).CreateCell(2).SetCellValue(5);

sheet.GetRow(2).CreateCell(2).SetCellValue(2);

//添加批注

IDrawing draw = sheet.CreateDrawingPatriarch();

IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 4));//里面参数应该是指示批注的位置大小吧

comment.String = new HSSFRichTextString("one-piece");//添加批注内容

comment.Author = "梦琪小生";//添加批注作者

sheet.GetRow(1).GetCell(1).CellComment = comment;//将之前设置的批注给定某个单元格

//单元格格式设置

ICellStyle cellStyle = workbook.CreateCellStyle();

IDataFormat format = workbook.CreateDataFormat();

cellStyle.DataFormat = format.GetFormat("0.00");

sheet.GetRow(2).GetCell(2).CellStyle = cellStyle;

//合并单元格

sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 2));

sheet.CreateRow(0).CreateCell(0).SetCellValue("梦琪小生");

ICellStyle titleStyle = workbook.CreateCellStyle();

IFont titleFont = workbook.CreateFont();

titleFont.FontHeightInPoints = 15;//设置字体大小

titleFont.Color = HSSFColor.BLUE.index;//设置字体颜色

titleStyle.SetFont(titleFont);

titleStyle.Alignment = HorizontalAlignment.CENTER;//居中

sheet.GetRow(0).GetCell(0).CellStyle = titleStyle;

ICellStyle style = workbook.CreateCellStyle();

style.BorderBottom = BorderStyle.THIN;

style.BorderLeft = BorderStyle.THIN;

style.BorderRight = BorderStyle.THIN;

style.BorderTop = BorderStyle.THIN;

sheet.GetRow(1).GetCell(1).CellStyle = style;

//插入图片

HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 0, 0, 0, 5, 6, 10);

byte[] bytes = System.IO.File.ReadAllBytes(@"C:\Users\Administrator\Desktop\image\mqxs.png");

int picID = workbook.AddPicture(bytes, PictureType.PNG);

IPicture pic = patriarch.CreatePicture(anchor2, picID);

pic.Resize();

workbook.Write(fs);//保存文件

}

}

读取Excel返回DataTable:

<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值