首页 > 代码库 > MVC FileDownLoad

MVC FileDownLoad

        public ActionResult MatDownload()
        {    
            string ShopId = Session["ShopId"].ToString();
            var selfStock = from c in db.stock_infolist
                            join d in db.bom on c.Stock_Sn equals d.Bom_Sn
                            where c.Stock_ShopID == ShopId && c.Stock_Code.Length <= 19
                            select new StockOut
                            {
                                Stock_Sn = c.Stock_Sn,
                                Bom_Type = d.Bom_Type,
                                Bom_Category = d.Bom_Category,
                                Bom_Name = d.Bom_Name,
                                Bom_Brand = d.Bom_Brand,
                                Bom_Model = d.Bom_Model,
                                Stock_Amount = c.Stock_Amount ?? 0,
                                Stock_Univalent = c.Stock_Univalent ?? 0,
                                SuggestedPrice = c.SuggestedPrice ?? 0
                            };
            var enList = selfStock.ToList();
            string url = "~/files/Out/Mat";
            string fileName = Server.MapPath(url + ".xlsx");//保存文件名
            string fileDName = Server.MapPath(url + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx");//下载文件名
            ExcelHandle eh = new ExcelHandle();
            eh.IListToExcel(enList, fileName, "已有物料", "店铺" + ShopId + "拥有的物料信息");//实现转换保存
            return File(fileName, "application/ms-excel", Url.Encode(Path.GetFileName(fileDName)));//发送文件到客户端
            }
        }
    }

1.LINQ从数据库获取数据,格式为List。

2.指定服务器端保存文件名,及客户端下载文件名。

3.调用ExcelHandle中的IListToExcel方法,完成转换及保存。

4.发送文件到客户端,View中直接调用MatDownload()方法即可实现下载。

MVC FileDownLoad