Ejemplo n.º 1
0
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportCommentsFile()
        {
            var ptcp = new BaseResponse {
                DoFlag = true, DoResult = ""
            };

            try
            {
                FileUploader uploader = new FileUploader("~/Upload");
                uploader.SetExtensionLimit(".xls|.xlsx");
                string        error;
                List <string> filenames = uploader.Process(this.Request, out error);
                string        fileName  = filenames.FirstOrDefault();
                if (!string.IsNullOrEmpty(error))
                {
                    ptcp.DoFlag   = false;
                    ptcp.DoResult = error;
                }
                else
                {
                    fileName = Path.GetFileName(fileName);
                    string fullPath = Path.Combine(Server.MapPath("~/Upload"), fileName);
                    //将excel数据导入到列表中
                    ImportExcelToList import = new ImportExcelToList();
                    MessageList       errors = new MessageList();
                    //获取表数据
                    ImportToListResult importedResult = import.DoImport(fullPath);
                    if (importedResult.Result.IsSuccess)
                    {
                        //获取验证返回的错误信息
                        errors.Merge(DoValidData(importedResult.Data.ImportedBody));
                        if (errors.Messages != null && errors.Messages.Any())
                        {
                            ptcp.DoFlag       = false;
                            ViewBag.ErrorMsgs = errors.Messages.Select(s => s.Message).ToList();
                        }
                        else
                        {
                            //执行导入
                            Stopwatch during = new Stopwatch();
                            during.Start();
                            int success = DoImport(importedResult.Data.ImportedHeader, importedResult.Data.ImportedBody);
                            during.Stop();
                            string info = success > 0?string.Format("导入成功!一共导入:{0}条记录,耗时{1}秒", success, during.Elapsed.TotalSeconds):"导入错误;插入失败";
                            ptcp.DoFlag   = success > 0;
                            ptcp.DoResult = info;
                        }
                    }
                    else
                    {
                        ptcp.DoFlag   = false;
                        ptcp.DoResult = importedResult.Result.Error;
                    }
                }
            }
            catch (Exception ex)
            {
                ptcp.DoFlag   = false;
                ptcp.DoResult = "导入异常";
            }

            ViewBag.Result = ptcp;
            return(View("ImportCommnets"));
        }