1. 程式人生 > >MVC中用NPOI匯出Excel相關問題

MVC中用NPOI匯出Excel相關問題

情形1:可以直接帶引數

前端頁面:

@.ActionLink("匯出Excel", "DownLoadExcel", new { 引數名= '引數值' }, new { style = "margin-right:10px;", @class = "btn btn-green search" })

style 和 class 都可以新增樣式

controller匯出方法(可以直接將Excel匯出 瀏覽器建議用谷歌)

方法如下:

public System.Web.Mvc.FileResult DownLoadExcel(string Id)

{

int ClassId = Convert.ToInt32(Request["
ClassId"]); string[] titleList = new string[] { "編號", "學員姓名", "單位", "聯絡方式", "身份證號碼", "繳費情況", "繳費方式", "所在班級", "備註資訊" }; IList<MODEL.Train.V_TrainProgramDetail> list = GetData()//獲取資料方法 //建立Excel檔案的物件 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //新增一個sheet NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("
Sheet1"); //給sheet1新增第一行的頭部標題 IRow headerrow = sheet1.CreateRow(0); HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle(); HSSFFont font = (HSSFFont)book.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); for (int i = 0; i < titleList.Length; i++) { ICell cell
= headerrow.CreateCell(i); cell.CellStyle = headStyle; cell.SetCellValue(titleList[i]); } //將資料逐步寫入sheet1各個行 for (int i = 0; i < list.Count; i++) { NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1); rowtemp.CreateCell(0).SetCellValue(list[i].Id.ToString()); rowtemp.CreateCell(1).SetCellValue(list[i].CompanyName); rowtemp.CreateCell(2).SetCellValue(list[i].CompanyName); rowtemp.CreateCell(3).SetCellValue(list[i].Phone); rowtemp.CreateCell(4).SetCellValue(list[i].IDCard); rowtemp.CreateCell(5).SetCellValue(list[i].IsPay.ToString()); rowtemp.CreateCell(6).SetCellValue(list[i].SignUpType.ToString()); rowtemp.CreateCell(7).SetCellValue(list[i].ClassName); rowtemp.CreateCell(8).SetCellValue(""); } // 寫入到客戶端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); return File(ms, "application/vnd.ms-excel", "學員報名詳情.xls");

}

情形2:不能直接帶引數,需要用到ajax

前端頁面:

         <div class="modal-content">
            <div class="modal-header" style="height:120px;">
                <button type="button" class="close" data-dissmiss="modal" aria-hidden="true" onclick="CancleImportExcel()">&times;</button>
                <h4 id="title">請選擇時間範圍</h4>
                <div class="modal-dialog container">
                    <div class="row">
                        <div class="col-xs-6">
                            <input  type="hidden" name="id" id="id" />
                            <label>訂單開始時間:</label>
                            <span>
                                <input type="text" id="OrderStartTime" name="OrderStartTime" onclick="WdatePicker({ dateFmt:'yyyy-MM-dd HH:mm:ss' })" class="Wdate" />
                            </span>
                        </div>
                        <div class="col-xs-6">
                            <label>結束時間:</label>
                            <span>
                                <input type="text" id="OrderEndTime" name="OrderEndTime" onclick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss' })" class="Wdate" />
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-default" data-dissmiss="modal" onclick="Export()">確定</button>
            </div>
        </div><script>

function Export() { var param = { OrderStartTime: $("#OrderStartTime").val(), OrderEndTime: $("#OrderEndTime").val() }; $.ajax({ url: '/Order/DownLoadExcel', //Controller名稱和方法名type: "POST",dataType: "json", data: param, success: function (data) {

//重定向返回引數 location.href = "/Order/OutExcel?guid=" + data; }  });}

</script>

Controller方法如下:

public ActionResult DownLoadExcel()
        {
            #region 查詢資料
            string OrderStartTime = Convert.ToDateTime(Request["OrderStartTime"]).ToString("yyyy-MM-dd");
            string OrderEndTime = Convert.ToDateTime(Request["OrderEndTime"]).AddDays(1).ToString("yyyy-MM-dd");

            string[] titleList = new string[] { "序號", "訂單編號", "收貨人", "送貨單位", "送貨地址", "商品編號", "商品名稱", "聯絡電話", "總價", "訂單狀態", "建立時間", "配送時間", "備註資訊" };
            IList<Model.Order.OrderInfo> list = OrderInfoBLL.GetOrdersInfoListByTime(OrderStartTime, OrderEndTime);
            #endregion

            #region NPOI資料匯出
            //建立Excel檔案的物件
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //新增一個sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //給sheet1新增第一行的頭部標題
            IRow headerrow = sheet1.CreateRow(0);

            HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle();
            HSSFFont font = (HSSFFont)book.CreateFont();
            font.FontHeightInPoints = 10;
            font.Boldweight = 700;
            headStyle.SetFont(font);
            for (int i = 0; i < titleList.Length; i++)
            {
                ICell cell = headerrow.CreateCell(i);
                cell.CellStyle = headStyle;
                cell.SetCellValue(titleList[i]);
            }
            //將資料逐步寫入sheet1各個行
            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(i + 1);
                rowtemp.CreateCell(1).SetCellValue(list[i].No);
                rowtemp.CreateCell(2).SetCellValue(list[i].Receiver);
                rowtemp.CreateCell(3).SetCellValue(list[i].Company);
                rowtemp.CreateCell(4).SetCellValue(list[i].Address);
                rowtemp.CreateCell(5).SetCellValue(list[i].CargoNo);
                rowtemp.CreateCell(6).SetCellValue(list[i].CargoName);
                rowtemp.CreateCell(7).SetCellValue(list[i].Phone);
                rowtemp.CreateCell(8).SetCellValue(list[i].Prices.ToString());
                rowtemp.CreateCell(9).SetCellValue(list[i].Status == 0 ? "待稽核" : list[i].Status == 1 ? "已稽核待收貨" : list[i].Status == 2 ? "已收貨已完成" : "取消稽核不通過");
                rowtemp.CreateCell(10).SetCellValue(list[i].CreateDate.ToString("yyyy-MM-dd"));
                rowtemp.CreateCell(11).SetCellValue(list[i].DeliveryTime.ToString("yyyy-MM-dd HH:mm"));
                rowtemp.CreateCell(12).SetCellValue("");
            }
            var guid = Guid.NewGuid().ToString();
            DownLoadHelper.SetCache(guid, book);
            return Json(guid, JsonRequestBehavior.AllowGet);
            #endregion
        }

public void OutExcel(string guid) { object obj = DownLoadHelper.GetCache(guid); NPOI.HSSF.UserModel.HSSFWorkbook book = obj as NPOI.HSSF.UserModel.HSSFWorkbook; if (book != null) { //寫入到客戶端 MemoryStream ms = new MemoryStream(); book.Write(ms); Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); Response.BinaryWrite(ms.ToArray()); book = null; ms.Close(); ms.Dispose(); } DownLoadHelper.RemoveAllCache(guid); }

就是在Controller不支援直接匯出Excel的時候  分兩步驟 1: 要先將匯出內容儲存在快取中 2: 利用ajax的重定向再將Excel資料匯出

下面是DownLoadHelper類方法:

public class DownLoadHelper
    {
        #region 獲取快取
        public static object GetCache(string cacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[cacheKey];
        }
        #endregion

        #region 設定資料快取
        public static void SetCache(string cacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject);
        }
        

        public static void SetCache(string cacheKey, object objObject, TimeSpan timeOut)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
        }

        public static void SetCache(string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }

        #endregion

        #region 移除資料快取
        public static void RemoveAllCache(string cacheKey)
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            _cache.Remove(cacheKey);
        }

        public static void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator cacheEnum = _cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                _cache.Remove(cacheEnum.Key.ToString());
            }
        }
        #endregion
    }

希望能對遇到此類問題的朋友有所幫助!