NPOI操作创建Excel

  一、下载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++;
            } 
       
       workBook.SetSheetOrder(sheet.SheetName, 0);//设置表格位置
       workBook.SetActiveSheet(0);//设置默认表格
       // 创建文件
            using (FileStream fs = new FileStream(string.Format("{0}/{1}", path, DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"), FileMode.Create))
            {
                workBook.Write(fs);
            }   

 

 

            

  

posted @ 2019-01-05 15:51  Tk、  阅读(2802)  评论(0编辑  收藏  举报