MVC Import .csv

时间:2015-11-18 06:48:39

标签: asp.net-mvc csv

控制器

    [HttpPost]
    public ActionResult Import(HttpPostedFileBase excelFile)
    {
        if (excelFile == null || excelFile.ContentLength == 0)
        {
            ViewBag.Error = "Please select a excel file<br>";
            return View("Index");
        }
        else
        {
            if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx") || excelFile.FileName.EndsWith("csv"))
            {

                string fileName = Path.GetFileName(excelFile.FileName);
                string path = Path.Combine(Server.MapPath("~/Content"), fileName);

                //string path = Server.MapPath("~/Content/" + excelFile.FileName);
                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
                excelFile.SaveAs(path);

                //Read data from excel file
                MExcel.Application application = new MExcel.Application();
                MExcel.Workbook workbook = application.Workbooks.Open(path);
                MExcel.Worksheet worksheet = workbook.ActiveSheet;
                MExcel.Range range = worksheet.UsedRange;
                List<PH> publicholidays = new List<PH>();

                for (int row = 0; row <= range.Rows.Count; row++)
                {
                    PH ph = new PH();
                    ph.Subject = ((MExcel.Range)range.Cells[row, 1]).Text;
                    ph.StartDate = ((MExcel.Range)range.Cells[row, 2]).Text;
                    ph.EndDate = ((MExcel.Range)range.Cells[row, 4]).Text;
                    publicholidays.Add(ph);
                }
                ViewBag.Publicholidays = publicholidays;
                return View("Success");
            }
            else
            {
                ViewBag.Error = "Incorrect file type<br>";
                return View("Index");
            }
        }
    }

我想导入一个.csv文件,但为什么当我尝试导入普通的.xls文件时它不起作用呢?我的代码有问题,还是我不能以这种方式导入.csv文件?

0 个答案:

没有答案