通過 NPOI 生成 Excel


        HSSFWorkbook hssfworkbook;
        ISheet sheet1;

        public void BuildExcel()
        {
            hssfworkbook = new HSSFWorkbook();
            // 新建一個Excel頁簽
            sheet1 = hssfworkbook.CreateSheet("Sheet1");

            // 創建新增行
            for (var i = 0; i < 10;i++ )
            {
                IRow row1 = sheet1.CreateRow(i);
                for (var j = 0; j < 10; j++)
                {
                    //新建單元格
                    ICell cell = row1.CreateCell(j);



                    // 單元格賦值
                    cell.SetCellValue("單元格"+j.ToString());
                }
            }
            
            // 設置行寬度
            sheet1.SetColumnWidth(2, 10 * 256);


            // 獲取單元格 並設置樣式
            ICellStyle styleCell = hssfworkbook.CreateCellStyle();
            //居中
            styleCell.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            //垂直居中 
            styleCell.VerticalAlignment = VerticalAlignment.Top;
            ICellStyle cellStyle = hssfworkbook.CreateCellStyle();

            //設置字體
            IFont fontColorRed = hssfworkbook.CreateFont();
            fontColorRed.Color = HSSFColor.OliveGreen.Red.Index;

            styleCell.SetFont(fontColorRed);

            
            sheet1.GetRow(2).GetCell(2).CellStyle = styleCell;

            // 合並單元格
            sheet1.AddMergedRegion(new CellRangeAddress(2, 4, 2, 5));


            // 輸出Excel
            string filename = "cnblogs.rhythmk.com.導出.xls";
            var context = HttpContext.Current;
            context.Response.ContentType = "application/vnd.ms-excel";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", context.Server.UrlEncode(filename)));
            context.Response.Clear();

           
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            context.Response.BinaryWrite(file.GetBuffer());
            context.Response.End();

          

        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM