当前位置: 移动技术网 > IT编程>开发语言>.net > NPOI操作创建Excel

NPOI操作创建Excel

2019年01月07日  | 移动技术网IT编程  | 我要评论

奇才公子,劲歌金曲颁奖礼,裴盹社

  一、下载npoi类库

    使用nuget在线搜索npoi,下载安装

  二、代码开撸

    

            var workbook = new hssfworkbook();

            #region 设置样式

            ifont font = workbook.createfont();
            font.fontheightinpoints = 11;
            font.fontname = "宋体";
            font.boldweight = (short)fontboldweight.bold;
            font.color = hssfcolor.white.index;

            hssfpalette palette = workbook.getcustompalette(); //调色板实例
            palette.setcoloratindex((short)8, (byte)91, (byte)155, (byte)213);//设置表头背景色
            palette.setcoloratindex((short)16, (byte)221, (byte)235, (byte)247);//设置内容背景色
            palette.setcoloratindex((short)32, (byte)155, (byte)194, (byte)230);//设置下边框线颜色
            palette.setcoloratindex((short)48, (byte)212, (byte)212, (byte)212);//设置下边框线颜色
            palette.setcoloratindex((short)64, (byte)255, (byte)255, (byte)0);//设置黄色            

            var cellmidstyle = workbook.createcellstyle();
            cellmidstyle.alignment = npoi.ss.usermodel.horizontalalignment.center;//设置水平居中
            cellmidstyle.verticalalignment = npoi.ss.usermodel.verticalalignment.center;//设置垂直居中
            cellmidstyle.fillpattern = fillpattern.solidforeground;
            cellmidstyle.fillforegroundcolor = palette.findcolor((byte)221, (byte)235, (byte)247).indexed;
            cellmidstyle.borderbottom = npoi.ss.usermodel.borderstyle.thin;
            cellmidstyle.bottombordercolor = palette.findcolor((byte)155, (byte)194, (byte)230).indexed;
            cellmidstyle.borderleft = npoi.ss.usermodel.borderstyle.thin;
            cellmidstyle.leftbordercolor = palette.findcolor((byte)212, (byte)212, (byte)212).indexed;
            cellmidstyle.setfont(font);
            #endregion
             
            var sheet = workbook.createsheet("sheet1");//创建表格
            // 第一行存放列名
            var row = sheet.createrow(0);
            for (int i = 0; i < titles.count; i++)
            {
                var cell = row.createcell(i);
                cell.setcellvalue(titles[i]);

                int length = encoding.utf8.getbytes(titles[i]).length;
                sheet.setcolumnwidth(i, length * 256);//设置表格列宽
                cell.cellstyle = cellstyle;//设置单元格样式
             }
            int rowindex = 1;
             foreach (var record in list)
            {
                row = sheet.createrow(rowindex);
                row.createcell(0).setcellvalue("单元格1");//给rowindex行的第1列的单元格赋值
                rowindex++;
            }
            // 创建文件
            using (filestream fs = new filestream(string.format("{0}/{1}", path, datetime.now.tostring("yyyymmddhhmmss") + ".xls"), filemode.create))
            {
                workbook.write(fs);
            }     

  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网