zoukankan      html  css  js  c++  java
  • 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,其他的东西你就自己研究吧。

  • 相关阅读:
    解决Odoo出现的Unable to send email, please configure the sender's email address or alias.
    Odoo误删除服务产品造成的错误解决办法
    Linux面试题汇总答案
    win7下安装openpyxl
    在Win7下使用sphinx-build建立开源软件文档
    如何把一个excel工作薄中N个工作表复制到另一个工作薄中
    如何手动添加Windows服务和如何把一个服务删除
    创建用户角色时出现的500错误问题解决方法
    odoo注销后在登录时的用户名和密码
    XenServer6.2详细安装步骤
  • 原文地址:https://www.cnblogs.com/lovewl2/p/11244389.html
Copyright © 2011-2022 走看看