c# .NET 使用MVC控制器導出Excel並打開

在MVC控制器中打開文件,需要用FileResult作爲控制器的返回值

 /// <summary>
        /// 導出Excel
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileResult ExportFile(string searchValue="",string payStatus="",string status="",string searchBeginDate="",string searchEndDate="") {
            string where = " IsDel=0";
            if (!String.IsNullOrEmpty(searchValue))
            {
                where += " and (PATINDEX('%" + searchValue + "%',OrderNo) > 0 " +
                    " or userid like '%" + searchValue + "%'" +
                    " or PATINDEX('%" + searchValue + "%',NickName) > 0 " +
                    " or PATINDEX('%" + searchValue + "%',CourseName) > 0) ";              
            }
            if (!String.IsNullOrEmpty(payStatus))
                where += " and PayStatus=" + payStatus;
            if (!String.IsNullOrEmpty(status))
                where += " and Status=" + status;
            if (!string.IsNullOrEmpty(searchBeginDate))
            {
                DateTime date1 = DateTime.Parse(searchBeginDate);
                where += " and CreatedOn > '" + date1 + "'";
            }
            if (!string.IsNullOrEmpty(searchEndDate))
            {
                DateTime date2 = DateTime.Parse(searchEndDate);
                where += " and CreatedOn < '" + date2 + "'";
            }
            //全部獲取
            DataTable dt = orderService.GetDataTable(where);
            if (dt.Rows.Count == 0) {
                //return Content("");
            }
         
            string folderSrc = "/Admin.Uploads/" + DateTime.Today.Date.ToString("yyyy-MM") + "/";
            if (!Directory.Exists(HttpContext.Server.MapPath(folderSrc)))
            {
                Directory.CreateDirectory(HttpContext.Server.MapPath(folderSrc));
            }
            Random rand = new Random();//隨生成器
            string fileName = folderSrc + DateTime.Now.Ticks + rand.Next(1000, 9999) + ".xls";
            string repath = HttpContext.Server.MapPath(fileName);
            string[] captions = {"機構名稱","訂單編號","用戶暱稱","手機號碼","班級名稱","課程名稱","訂單金額","優惠金額","需付金額","實付金額","付款時間","下單時間" };//列名
            MemoryStream ms = ExcelHelper.RenderToExcel(captions,dt,repath);
            return File(ms, "application/ms-excel","order.xls");
        }

下面是生成EXCEL的代碼,幫助類,傳DataTable,列名,保存路徑(會保存到服務器,不需要的話就刪掉保存這一步應該也可以,沒有試驗)進去,返回MemoryStream,
借用的是NPOI.dll插件

 /// <summary>
    /// Excel helper
    /// </summary>
    public partial class ExcelHelper  
    {  
        public static MemoryStream RenderToExcel(string [] captions, DataTable table,string fileName)
        {
    
            MemoryStream ms = new MemoryStream();
            using (table)
            {
                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                {
                    IRow headerRow = sheet.CreateRow(0);
                    for (int i = 0; i < captions.Length; i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(captions[i]);
                    } 
                    int rowIndex = 1;
                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
                        foreach (DataColumn column in table.Columns)
                        {
                            dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        }
                        rowIndex++;
                    }
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }
                FileStream file = new FileStream(fileName, FileMode.OpenOrCreate);
                workbook.Write(file);
                file.Close();
                return ms;
            }
        }
}

然後是前端調用控制器:js方法,按鈕直接調用,參數自定義

        function exportExcel() {
            window.location.href = "/Business/Order/ExportFile?searchValue=" + searchValue +
                "&status=" + status + "&payStatus=" + payStatus + "&searchBeginDate=" + searchBeginDate + "&searchEndDate=" + searchEndDate; 
        }

ps:最討厭那些發代碼不發全還不說前端怎麼調用的人,我也是新手,找了很多導出的資料,結果發現很多隻能保存到服務器,不會保存到客服端,後面才發現MVC裏面用法不一樣,找了半天才找到方法,然後發現很多沒說怎麼調用,作爲小菜鳥是真的不知道,因爲一向都是用ajax調用控制器,處理返回結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章