NPOI操作EXCEL

//说明:HSSFWorkbook 用于创建 .xls
// XSSFWorkbook 用于创建 .xlsx

//1.创建EXCEL中的Workbook
IWorkbook myHSSFworkbook = new HSSFWorkbook();
IWorkbook myXSSFworkbook = new XSSFWorkbook();

//2.创建Workbook中的Sheet
ISheet mysheetHSSF = myHSSFworkbook.CreateSheet("sheet1");
ISheet mysheetXSSF = myXSSFworkbook.CreateSheet("sheet1");

//3.创建Sheet中的Row
IRow rowHSSF = mysheetHSSF.CreateRow(0);
//SetCellValue有5个重载方法 bool、DateTime、double、string、IRichTextString(未演示)
rowHSSF.CreateCell(0).SetCellValue(true);
rowHSSF.CreateCell(1).SetCellValue(System.DateTime.Now);
rowHSSF.CreateCell(2).SetCellValue(9.32);
rowHSSF.CreateCell(3).SetCellValue("Hello World!");

//4.创建Row中的Cell并赋值
IRow rowXSSF = mysheetXSSF.CreateRow(0);
rowXSSF.CreateCell(0).SetCellValue(false);
rowXSSF.CreateCell(1).SetCellValue(System.DateTime.Now);
rowXSSF.CreateCell(2).SetCellValue(9.32);
rowXSSF.CreateCell(3).SetCellValue("Hello World!");

//5.保存
FileStream fileHSSF = new FileStream(@"E:\myHSSFworkbook.xls", FileMode.Create);
myHSSFworkbook.Write(fileHSSF);
fileHSSF.Close();

FileStream fileXSSF = new FileStream(@"E:\myXSSFworkbook.xlsx", FileMode.Create);
myXSSFworkbook.Write(fileXSSF);
fileXSSF.Close();

//6.合并单元格【CellRangeAddress(开始行,结束行,开始列,结束列)】
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("第四列");

//7.设置列宽【SetColumnWidth(列索引,N*256) 第二个参数是列宽 单位是1/256个字符宽度】
mysheetHSSF.SetColumnWidth(3, 30 * 256); //设置第四列的列宽为30个字符

//8.设置行高【Height的单位是1/20个点】
SecondRowHSSF.Height=50*20; //设置高度为50个点

//9.设置单元格对齐方式
IRow ThirdRowHSSF = mysheetHSSF.CreateRow(2);
ThirdRowHSSF.Height = 50 * 20;
ThirdRowHSSF.CreateCell(0).SetCellValue("默认对齐");
ThirdRowHSSF.CreateCell(1).SetCellValue("左对齐");
ThirdRowHSSF.CreateCell(2).SetCellValue("居中");
ThirdRowHSSF.CreateCell(3).SetCellValue("右对齐");
IRow FourthRowHSSF = mysheetHSSF.CreateRow(3);
FourthRowHSSF.Height = 50 * 20;
FourthRowHSSF.CreateCell(0).SetCellValue("填充单元格");
FourthRowHSSF.CreateCell(1).SetCellValue("she zhi dan yuan ge liang duan dui qi");
FourthRowHSSF.CreateCell(2).SetCellValue("跨列居中");
FourthRowHSSF.CreateCell(3).SetCellValue("分散对齐");

//创建CellStyle
ICellStyle style0 = myHSSFworkbook.CreateCellStyle();
style0.Alignment = HorizontalAlignment.General;//【General】数字、时间默认:右对齐;BOOL:默认居中;字符串:默认左对齐

ICellStyle style1 = myHSSFworkbook.CreateCellStyle();
style1.Alignment = HorizontalAlignment.Left;//【Left】左对齐

ICellStyle style2 = myHSSFworkbook.CreateCellStyle();
style2.Alignment = HorizontalAlignment.Center;//【Center】居中

ICellStyle style3 = myHSSFworkbook.CreateCellStyle();
style3.Alignment = HorizontalAlignment.Right;//【Right】右对齐

ICellStyle style4 = myHSSFworkbook.CreateCellStyle();
style4.Alignment = HorizontalAlignment.Fill;//【Fill】填充

ICellStyle style5 = myHSSFworkbook.CreateCellStyle();
style5.Alignment = HorizontalAlignment.Justify;//【Justify】两端对齐[会自动换行](主要针对英文)
ICellStyle style6 = myHSSFworkbook.CreateCellStyle();
style6.Alignment = HorizontalAlignment.CenterSelection;//【CenterSelection】跨列居中

ICellStyle style7 = myHSSFworkbook.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;

//10.设置单元格背景与图案【Pattern的填充图案没有演示全,下面的图片是效果图】
IRow FifthRowHSSF = mysheetHSSF.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 = myHSSFworkbook.CreateCellStyle(); Blackstyle0.FillBackgroundColor = IndexedColors.White.Index;
Blackstyle0.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle0.FillPattern = FillPattern.NoFill;
FifthRowHSSF .GetCell(0).CellStyle = Blackstyle0;
ICellStyle Blackstyle1 = myHSSFworkbook.CreateCellStyle(); Blackstyle1.FillBackgroundColor = IndexedColors.White.Index;
Blackstyle1.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle1.FillPattern = FillPattern.SolidForeground;
FifthRowHSSF .GetCell(1).CellStyle = Blackstyle1;
ICellStyle Blackstyle2 = myHSSFworkbook.CreateCellStyle(); Blackstyle2.FillBackgroundColor = IndexedColors.White.Index;
Blackstyle2.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle2.FillPattern = FillPattern.FineDots;
FifthRowHSSF .GetCell(2).CellStyle = Blackstyle2;
ICellStyle Blackstyle3 = myHSSFworkbook.CreateCellStyle(); Blackstyle3.FillBackgroundColor = IndexedColors.White.Index;
Blackstyle3.FillForegroundColor = IndexedColors.Blue.Index; Blackstyle3.FillPattern = FillPattern.AltBars;
FifthRowHSSF .GetCell(3).CellStyle = Blackstyle3;

//11.设置单元格边框
ICellStyle BorderStyle = myworkbook.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 = myworkbook.CreateCellStyle();
BorderStyle1.BorderDiagonalLineStyle = BorderStyle.Thin;//BorderDiagonalLineStyle对角线样式 Thin细线
BorderStyle1.BorderDiagonal = BorderDiagonal.Backward;//反向【Forward正向;Both两条线】
BorderStyle1.BorderDiagonalColor = IndexedColors.Red.Index;//红线

//12.设置Excel字体
//设置字体样式
IFont font = myworkbook.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 = myHSSFworkbook.CreateCellStyle();
Fontstyle.SetFont(font);

//13.设置单元格数字格式
//创建CellStyle与DataFormat并加载格式样式
IDataFormat dataformat = myworkbook.CreateDataFormat();
ICellStyle Numstyle = myworkbook.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表示精确到显示小数点后几位】

//14.设置单元格时间格式
//创建CellStyle与DataFormat并加载格式样式
IDataFormat dataformat = myworkbook.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 = myworkbook.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 下午】

//15.设置单元格文本格式
IDataFormat dataformat = myworkbook.CreateDataFormat();

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

//16.插入图片
//第一步:读取图片到byte数组
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://img1.soufunimg.com/message/images/card/tuanproj/201511/2015112703584458_s.jpg");
byte[] bytes;
using (Stream stream = request.GetResponse().GetResponseStream())
{
using (MemoryStream mstream = new MemoryStream())
{
int count = 0;
byte[] buffer = new byte[1024];
int readNum = 0;
while ((readNum = stream.Read(buffer, 0, 1024)) > 0)
{
count = count + readNum;
mstream.Write(buffer, 0, 1024);
}
mstream.Position = 0;
using (BinaryReader br = new BinaryReader(mstream))
{

bytes = br.ReadBytes(count);
}
}
}

//第二步:将图片添加到workbook中 指定图片格式 返回图片所在workbook->Picture数组中的索引地址(从1开始)
int pictureIdx = myworkbook.AddPicture(bytes, PictureType.JPEG);

//第三步:在sheet中创建画部
IDrawing patriarch = mysheet.CreateDrawingPatriarch();
//第四步:设置锚点 (在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)
IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, 0, 0, 2, 2);
//第五步:创建图片
IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);

//17.批注
HSSFPatriarch patr = sheet.CreateDrawingPatriarch();
HSSFComment comment1 = patr.CreateComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2 , 4, 4));
comment1.String=new HSSFRichTextString("Hello World");
comment1.Author="NPOI Team";
HSSFCell cell= sheet.CreateRow(1).CreateCell(1);
cell.CellComment= comment1;
对于批注,你有两种选择,一种是隐藏(默认),一种是显示(即表单一打开就显示该批注),可以通过comment1.Visible属性来控制。

//18.设置页眉和页脚
很多人并不知道Excel的页眉和页脚功能,因为在界面上是显示不了页眉和页脚的,必须在打印页面中才能看到,这也直接导致了其设置界面也显得更隐秘,你必须进入页面设置 –>页眉和页脚才能设置。
以下是Office 2007中的设置界面。
当你按“自定义页眉”或“自定义页脚”时,你会看到以下界面,Excel把页眉、页脚分成了左中右三部分,这一点绝非单纯体现在界面上,在底层的存储中也是如此。
如果你设置的是“左”的内容,底层的存储字符串就会在开头加上&L,如果是“右”的内容则会加上&R,所以HeaderRecord中的字符串看上去是这样的:"&C&LFooter A&R”,这个字符串的意思是仅设置了“左”的内容,内容是Footer A。
看了这些我想你应该对页眉和页脚有所了解了,回过头来说NPOI,NPOI中主要是靠HSSFSheet.Header和HSSFSheet.Footer来设置的,这两个属性分别是HSSFHeader和HSSFFooter类型的。
参考代码如下:
HSSFSheet s1= hssfworkbook.CreateSheet("Sheet1");
s1.CreateRow(0).CreateCell(1).SetCellValue(123);
//set headertext
s1.Header.Center="This is a test sheet";
//set footertext
s1.Footer.Left="Copyright NPOI Team";
s1.Footer.Right="created by Tony Qu(瞿杰)";
以上代码中我添加了页眉的Center内容,Footer的Left和Right内容
至于一些Excel特殊字符,比如说页码可以用&P,当前日期可以用&D,其他的东西你就自己研究吧。

 

转载于:https://www.cnblogs.com/lovewl2/p/11244389.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 NPOI 操作 Excel,可以通过设置行高的方式来自动调整行高。具体步骤如下: 1. 获取工作表对象: ```csharp ISheet sheet = workbook.GetSheet("Sheet1"); ``` 2. 创建单元格样式对象: ```csharp ICellStyle style = workbook.CreateCellStyle(); ``` 3. 设置单元格样式对象的自动换行属性为 true: ```csharp style.WrapText = true; ``` 4. 遍历需要设置行高的行,计算每行的高度并设置: ```csharp for (int i = 0; i < sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row != null) { row.HeightInPoints = sheet.DefaultRowHeightInPoints; int numLines = 1; foreach (ICell cell in row.Cells) { if (cell != null && cell.CellType == CellType.String) { string text = cell.StringCellValue; if (text.Contains("\n")) { numLines = Math.Max(numLines, text.Split('\n').Length); } } } row.HeightInPoints = sheet.DefaultRowHeightInPoints * numLines; } } ``` 其中,`sheet.DefaultRowHeightInPoints` 表示默认行高,`numLines` 表示行中需要显示的行数。在遍历每个单元格时,如果单元格中包含换行符 `\n`,则计算需要显示的行数。最后将计算得到的行高设置给该行即可。 完整代码示例如下: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.IO; namespace NPOIDemo { class Program { static void Main(string[] args) { using (FileStream stream = new FileStream("test.xlsx", FileMode.Open, FileAccess.ReadWrite)) { XSSFWorkbook workbook = new XSSFWorkbook(stream); ISheet sheet = workbook.GetSheet("Sheet1"); ICellStyle style = workbook.CreateCellStyle(); style.WrapText = true; for (int i = 0; i < sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row != null) { row.HeightInPoints = sheet.DefaultRowHeightInPoints; int numLines = 1; foreach (ICell cell in row.Cells) { if (cell != null && cell.CellType == CellType.String) { string text = cell.StringCellValue; if (text.Contains("\n")) { numLines = Math.Max(numLines, text.Split('\n').Length); } } } row.HeightInPoints = sheet.DefaultRowHeightInPoints * numLines; } } workbook.Write(stream); } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值