NPOI生成excel並下載


NPOI文件下載地址:http://npoi.codeplex.com/

將文件直接引用至項目中即可,,,,,

雖然網上資料很多,但有可能並找不到自己想要的功能,今天閑的沒事,所以就稍微整理了一個簡單的例子,希望自己在以后的項目中用得着,到時候就不用在網上查找了,直接把代碼copy過來就可以啦~~~~主要是在mvc控制器里面敲的,直接貼代碼了。。。。。

1、邏輯代碼

 public EmptyResult ExportExcle()
        {
            HSSFCellStyle style;
            HSSFFont font;
#if DEBUG
            UserInfo u = new UserInfo();
            List<UserInfo> list = u.GetDate();
            string url = Server.MapPath(@"\Content\File\MyBook.xls");
            string sheetName = "MySheet";
#endif
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            FileStream filecreate = new FileStream(url, FileMode.Create, FileAccess.ReadWrite);
            //創建工作表
            HSSFSheet sheet = hssfworkbook.CreateSheet(sheetName) as HSSFSheet;
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("用戶編號");
            row.CreateCell(1).SetCellValue("用戶名");
            row.CreateCell(2).SetCellValue("性別");
            row.CreateCell(3).SetCellValue("年齡");
            row.CreateCell(4).SetCellValue("電話");
            row.CreateCell(5).SetCellValue("身份證");
            //行高
            row.HeightInPoints = 20;
            //給表頭單元格設置樣式(對齊方式、邊框、字體、背景顏色)
            List<ICell> cell = row.Cells;
            style = hssfworkbook.CreateCellStyle() as HSSFCellStyle;
            font = hssfworkbook.CreateFont() as HSSFFont;
            font.IsBold = true;//加粗
            font.FontName = "宋體";
            font.Color = HSSFColor.Red.Index;//字體顏色
            style.SetFont(font);
            this.CellStyle(style, sheet);
            style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index;
            style.FillPattern = FillPattern.SolidForeground;
            cell.ForEach(delegate(ICell c)
            {
                c.CellStyle = style;
            });

            //加載內容
            if (list.Any())
            {
                style = hssfworkbook.CreateCellStyle() as HSSFCellStyle;
                this.CellStyle(style, sheet);
                for (int i = 0; i < list.Count; i++)
                {
                    row = sheet.CreateRow(i + 1);
                    row.HeightInPoints = 20;
                    row.CreateCell(0).SetCellValue(list[i].UserId);
                    row.CreateCell(1).SetCellValue(list[i].UserName);
                    row.CreateCell(2).SetCellValue(list[i].Sex);
                    row.CreateCell(3).SetCellValue(list[i].Age);
                    row.CreateCell(4).SetCellValue(list[i].Tel);
                    row.CreateCell(5).SetCellValue(list[i].IdCard);
                    cell = row.Cells;
                    cell.ForEach(p => p.CellStyle = style);
                }
            }
            //將流寫入excel文件
            hssfworkbook.Write(filecreate);
            filecreate.Close();

            #region 下載文件
            FileStream fileopen = new FileStream(url, FileMode.Open);
            byte[] bytes = new byte[(int)fileopen.Length];
            fileopen.Read(bytes, 0, bytes.Length);
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("MyBook.xls", System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            fileopen.Close();
            Response.Flush();
            Response.End();
            return new EmptyResult();
            #endregion
        }

 2、單元格樣式

        /// <summary>
        /// 樣式
        /// </summary>
        /// <param name="style"></param>
        /// <param name="sheet"></param>
        private void CellStyle(HSSFCellStyle style, HSSFSheet sheet)
        {
            //自動換行
            style.WrapText = true;
            //邊框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;
            //對齊方式
            style.Alignment = HorizontalAlignment.Center;
            style.VerticalAlignment = VerticalAlignment.Center;
            //設置第四列、第五列的寬度
            sheet.SetColumnWidth(4, 20 * 256);
            sheet.SetColumnWidth(5, 30 * 256);
        }

3、數據源

private class UserInfo
        {
            public int UserId { get; set; }
            public string UserName { get; set; }
            public string Sex { get; set; }
            public int Age { get; set; }
            public string Tel { get; set; }
            public string IdCard { get; set; }

            public List<UserInfo> GetDate()
            {
                List<UserInfo> list = new List<UserInfo>() 
                {
                 new UserInfo{UserId=1,UserName="張三",Sex="",Age=20,Tel="18217722343",IdCard="150726198810235436"},
                 new UserInfo{UserId=2,UserName="李四",Sex="",Age=23,Tel="18217722343",IdCard="150726198810235436"},
                 new UserInfo{UserId=3,UserName="王五",Sex="",Age=21,Tel="18217722343",IdCard="150726198810235436"},
                 new UserInfo{UserId=4,UserName="趙六",Sex="",Age=30,Tel="18217722343",IdCard="150726198810235436"},
                 new UserInfo{UserId=5,UserName="錢七",Sex="",Age=45,Tel="18217722343",IdCard="150726198810235436"},
                 new UserInfo{UserId=6,UserName="張三",Sex="",Age=18,Tel="18217722343",IdCard="150726198810235436"}
                };
                return list;
            }
        }

4、前端代碼

之前遇到了一個問題,因為剛開始我使用的是Ajax方式提交的,所以在瀏覽器上無法看到下載提示框,最后搞了半天,原來是因為提交方式不對,換成location就可以了。

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnExportExcle").click(function () {
                //var options = {
                //    type: 'get',
                //    cache: false,
                //    async:false,
                //    url: '/Index/ExportExcle',
                //    success: function (data) {
                //    }
                //};
                //$.ajax(options);
                location = "/Index/ExportExcle";
            });
        });
    </script>
</head>
<body>
    <input type="button" value="導出Excel" id="btnExportExcle" />
</body>
</html>

5、前台頁面效果

 

6、打開Excel

好了,就介紹到這里了,希望對大家也有所幫助~~~~

 


免責聲明!

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



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