C# NPOI 导出以及样式设定

IWorkbook workbook2003 = new HSSFWorkbook();//创建.xls

IWorkbook workbook2007 = new XSSFWorkbook();//.xlsx

ISheet sheet1 = workbook2003.CreateSheet(sheetname);//创建工作表

IRow row = sheet1.CreateRow(int);//创建行//最大数据量不能超过65536.xls 最大数据量不能超 1048576.xlsx

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

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

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

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

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

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

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

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

设置单元格对齐方式 

IRow ThirdRowHSSF = workbook2003.CreateRow(2); 
ThirdRowHSSF.Height = 50 * 20; 
ThirdRowHSSF.CreateCell(0).SetCellValue("默认对齐"); 
ThirdRowHSSF.CreateCell(1).SetCellValue("左对齐"); 
ThirdRowHSSF.CreateCell(2).SetCellValue("居中"); 
ThirdRowHSSF.CreateCell(3).SetCellValue("右对齐");
IRow FourthRowHSSF = workbook2003.CreateRow(3);
FourthRowHSSF.Height = 50 * 20;
FourthRowHSSF.CreateCell(0).SetCellValue("填充单元格");
FourthRowHSSF.CreateCell(1).SetCellValue("设置单元格两端对齐");
FourthRowHSSF.CreateCell(2).SetCellValue("跨列居中");
FourthRowHSSF.CreateCell(3).SetCellValue("分散对齐");
ICellStyle style0 = workbook2003.CreateCellStyle();//创建CellStyle 
//【General】数字、时间默认:右对齐;BOOL:默认居中;字符串:默认左对齐
style0.Alignment = HorizontalAlignment.General;
ICellStyle style1 = workbook2003.CreateCellStyle();
style1.Alignment = HorizontalAlignment.Left;//【Left】左对齐 
ICellStyle style2 = workbook2003.CreateCellStyle();
style2.Alignment = HorizontalAlignment.Center;//【Center】居中
ICellStyle style3 = workbook2003.CreateCellStyle();
style3.Alignment = HorizontalAlignment.Right;//【Right】右对齐 
ICellStyle style4 = workbook2003.CreateCellStyle();
style4.Alignment = HorizontalAlignment.Fill;//【Fill】填充
ICellStyle style5 = workbook2003.CreateCellStyle();
//【Justify】两端对齐[会自动换行](主要针对英文)
style5.Alignment = HorizontalAlignment.Justify;
ICellStyle style6 = workbook2003.CreateCellStyle();
style6.Alignment = HorizontalAlignment.CenterSelection;//【CenterSelection】跨列居中
ICellStyle style7 = workbook2003.CreateCellStyle();
style7.Alignment = HorizontalAlignment.Distributed;//【Distributed】分散对齐[会自动换行]
//【Tips】
// 1.通过ICellStyle的VerticalAlignment属性可以设置垂直对齐模式与水平对齐无异 不再演示 
// 2.通过ISheet的SetDefaultColumnStyle(int column, ICellStyle style)方法可以设置整列的默认单元格样式;
//将CellStyle应用于具体单元格
ThirdRowHSSF.GetCell(0).CellStyle = style0;
ThirdRowHSSF.GetCell(1).CellStyle = style1;
ThirdRowHSSF.GetCell(2).CellStyle = style2;
ThirdRowHSSF.GetCell(3).CellStyle = style3;
FourthRowHSSF.GetCell(0).CellStyle = style4;
FourthRowHSSF.GetCell(1).CellStyle = style5;
FourthRowHSSF.GetCell(2).CellStyle = style6;
FourthRowHSSF.GetCell(3).CellStyle = style7;

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

IRow FifthRowHSSF = workbook2003.CreateRow(4);
FifthRowHSSF.CreateCell(0).SetCellValue("NoFill");
FifthRowHSSF.CreateCell(1).SetCellValue("SolidForeground");
FifthRowHSSF.CreateCell(2).SetCellValue("FineDots"); 
FifthRowHSSF.CreateCell(3).SetCellValue("AltBars"); 
//【Tips】
// 1.ForegroundColor(默认黑色)【前景颜色】BackgroundColor(默认为前景颜色的反色)【背景颜色】Pattern(必须指定,默认NoFill)【填充的图案】
// 2.演示中使用 【前景颜色】蓝色 【背景颜色】白色 
//创建CellStyle并应用于单元格
ICellStyle Blackstyle0 = workbook2003.CreateCellStyle();
Blackstyle0.FillBackgroundColor = IndexedColors.White.Index;
FifthRowHSSF .GetCell(0).CellStyle = Blackstyle0;
Blackstyle0.FillForegroundColor = IndexedColors.Blue.Index;
Blackstyle0.FillPattern = FillPattern.NoFill;
ICellStyle Blackstyle1 = workbook2003.CreateCellStyle();
Blackstyle1.FillBackgroundColor = IndexedColors.White.Index;
Blackstyle1.FillForegroundColor = IndexedColors.Blue.Index;
Blackstyle1.FillPattern = FillPattern.SolidForeground;
FifthRowHSSF .GetCell(1).CellStyle = Blackstyle1;
ICellStyle Blackstyle2 = workbook2003.CreateCellStyle();
Blackstyle2.FillBackgroundColor = IndexedColors.White.Index;
Blackstyle2.FillForegroundColor = IndexedColors.Blue.Index;
Blackstyle2.FillPattern = FillPattern.FineDots;
FifthRowHSSF.GetCell(2).CellStyle = Blackstyle2;
ICellStyle Blackstyle3 = workbook2003.CreateCellStyle();
Blackstyle3.FillBackgroundColor = IndexedColors.White.Index;
Blackstyle3.FillForegroundColor = IndexedColors.Blue.Index;
Blackstyle3.FillPattern = FillPattern.AltBars;
FifthRowHSSF.GetCell(3).CellStyle = Blackstyle3;

设置单元格边框

ICellStyle BorderStyle = workbook2003.CreateCellStyle(); 
BorderStyle .BorderBottom = BorderStyle.Thin;//设置单元格低边框为细线 
//BorderStyle.Medium;【中等线】 
//BorderStyle.Dashed;【虚线】 
//BorderStyle.Dotted;【斑点线】 
//BorderStyle.Thick;【粗线】 
//BorderStyle.Double;【双线】
//BorderStyle.Hair;【多点线】
//BorderStyle.MediumDashed;【中等虚线】
//BorderStyle.DashDot;【点线】
//BorderStyle.MediumDashDot;【中等点线】
//BorderStyle.DashDotDot;【双点划线】
//BorderStyle.MediumDashDotDot;【中等双点划线】
//BorderStyle.SlantedDashDot;【倾斜的点划线】ICellStyle BorderStyle1 = workbook2003.CreateCellStyle(); 
BorderStyle1.BorderDiagonalLineStyle = BorderStyle.Thin;
//BorderDiagonalLineStyle对角线样式 Thin细线BorderStyle1.BorderDiagonal = BorderDiagonal.Backward;//反向【Forward正向;Both两条线】BorderStyle1.BorderDiagonalColor = IndexedColors.Red.Index;//红线

设置Excel字体

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

设置单元格数字格式

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

设置单元格时间格式 

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

设置单元格文本格式

IDataFormat dataformat = workbook2003.CreateDataFormat();
//【Tips】   使用@ 或 text 都可以
ICellStyle Textstyle = myworkbook.CreateCellStyle();
Textstyle.DataFormat = dataformat.GetFormat("@");
//dataformat.GetFormat("text");

插入图片

 //第一步:读取图片到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 = workbook2003.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);

保存Excel

 FileStream fileStream = File.OpenWrite(strPathFile);
 workbook2003.Write(fileStream);
 ileStream.Close();
 workbook2003.Close();

参考:https://blog.51cto.com/u_15057843/2635635

  • 10
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用C#和NPOI库可以方便地导出Excel表格。下面是一个简单的示例: 1. 首先,你需要安装NPOI库,可以使用NuGet包管理器进行安装。 2. 在代码中,首先创建一个工作簿和一个工作表: ``` using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; ... // 创建一个工作簿 var workbook = new XSSFWorkbook(); // 创建一个工作表 var sheet = workbook.CreateSheet("Sheet1"); ``` 3. 接下来,你可以向表格中添加数据。以下是将数据添加到第一行的示例: ``` // 创建第一行并添加数据 var headerRow = sheet.CreateRow(0); headerRow.CreateCell(0).SetCellValue("ID"); headerRow.CreateCell(1).SetCellValue("Name"); headerRow.CreateCell(2).SetCellValue("Age"); ``` 4. 然后,你可以循环遍历数据并将其添加到表格中。以下是将数据添加到第二行和第三行的示例: ``` // 模拟数据 var data = new List<Person> { new Person { ID = 1, Name = "Alice", Age = 18 }, new Person { ID = 2, Name = "Bob", Age = 20 } }; // 循环遍历数据 for (int i = 0; i < data.Count; i++) { var row = sheet.CreateRow(i + 1); row.CreateCell(0).SetCellValue(data[i].ID); row.CreateCell(1).SetCellValue(data[i].Name); row.CreateCell(2).SetCellValue(data[i].Age); } ``` 5. 最后,将工作簿保存到文件中: ``` // 保存工作簿到文件 using (var fileStream = new FileStream("output.xlsx", FileMode.Create)) { workbook.Write(fileStream); } ``` 完整的代码示例: ``` using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.Collections.Generic; using System.IO; class Person { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } ... // 创建一个工作簿 var workbook = new XSSFWorkbook(); // 创建一个工作表 var sheet = workbook.CreateSheet("Sheet1"); // 创建第一行并添加数据 var headerRow = sheet.CreateRow(0); headerRow.CreateCell(0).SetCellValue("ID"); headerRow.CreateCell(1).SetCellValue("Name"); headerRow.CreateCell(2).SetCellValue("Age"); // 模拟数据 var data = new List<Person> { new Person { ID = 1, Name = "Alice", Age = 18 }, new Person { ID = 2, Name = "Bob", Age = 20 } }; // 循环遍历数据 for (int i = 0; i < data.Count; i++) { var row = sheet.CreateRow(i + 1); row.CreateCell(0).SetCellValue(data[i].ID); row.CreateCell(1).SetCellValue(data[i].Name); row.CreateCell(2).SetCellValue(data[i].Age); } // 保存工作簿到文件 using (var fileStream = new FileStream("output.xlsx", FileMode.Create)) { workbook.Write(fileStream); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值