码迷,mamicode.com
首页 > Web开发 > 详细

net core 上传并使用EPPlus导入Excel文件

时间:2018-06-20 12:49:29      阅读:863      评论:0      收藏:0      [点我收藏+]

标签:data   bin   environ   save   限制   epp   count   col   lse   

1.  cshtml页面 form

<form id="form" method="post" action="/SaveValueBatch"
      enctype="multipart/form-data">
<input type="file" name="uploadExcel" style="width:200px;" />
</form>

2. controller

        [HttpPost]
        public ActionResult SaveValueBatch(IFormCollection form)
        {
            try
            {
                var files =Request.Form.Files.Where(x => x.Name.Equals("uploadExcel"));

                //非空限制
                if (files == null || files.Count() <= 0) { return Json(new { isSuccess = false, message = "请选择要上传的Excel文件" }, "text/html"); }

                //格式限制
                var allowType = new string[] { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
                if (files.Any(b => !allowType.Contains(b.ContentType)))
                {
                    return Json(new { isSuccess = false, message = "只能上传Excel 2007 格式文件" }, "text/html");
                }

                //大小限制
                if (files.Sum(b => b.Length) >= 1024 * 1024 * 4)
                {
                    return Json(new { isSuccess = false, message = "上传文件的总大小只能在4M以下" }, "text/html");
                }

                //写入服务器磁盘
                foreach (var file in files)
                {

                    var fileName = file.FileName;
                    var path = Path.Combine(_host.ContentRootPath+ "/Upload", fileName);
                    using (var stream = System.IO.File.Create(path))
                    {
                        file.CopyTo(stream);
                    }
                }
                return Json(new { isSuccess = true, message = "保存成功" }, "text/html");
            }
            catch (Exception e)
            {
               
                return Json(new { isSuccess = false, message = "保存失败:" + e.InnerException.Message }, "text/html");
            }
        }
        private IHostingEnvironment _host;

        public ExcelController(IHostingEnvironment host)
        {
            _host = host;
        }

 

net core 上传并使用EPPlus导入Excel文件

标签:data   bin   environ   save   限制   epp   count   col   lse   

原文地址:https://www.cnblogs.com/zitjubiz/p/net_core_epplus_excel_upload.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!