MVC 4将Excel文件上传到数据库

时间:2017-07-18 10:17:54

标签: excel asp.net-mvc-4 file-upload

遇到这个问题 'HttpRequest'不包含'Files'的定义,也没有扩展方法'Files'可以找到'HttpRequest'类型的第一个参数(你是否缺少using指令或汇编引用?)

不知道如何转换此行的日期

user.StudentDob = workSheet.Cells [rowIterator,6] .Value.ToString();

任何人都可以提供帮助?尝试上传excel文件进​​行阅读。

这是我的控制器

public ActionResult Upload(FormCollection formCollection)
    {
        if (Request != null)
        {
            HttpPostedFileBase file = Request.Files["UploadedFile"];
            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                string fileName = file.FileName;
                string fileContentType = file.ContentType;
                byte[] fileBytes = new byte[file.ContentLength];
                var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                var usersList = new List<Student>();
                using (var package = new ExcelPackage(file.InputStream))
                {
                    var currentSheet = package.Workbook.Worksheets;
                    var workSheet = currentSheet.First();
                    var noOfCol = workSheet.Dimension.End.Column;
                    var noOfRow = workSheet.Dimension.End.Row;

                    for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                    {
                        var user = new Student();
                        user.StudentId = workSheet.Cells[rowIterator, 1].Value.ToString().FirstOrDefault();
                        user.StudentNric = workSheet.Cells[rowIterator, 2].Value.ToString();
                        user.StudentName = workSheet.Cells[rowIterator, 3].Value.ToString();
                        user.StudentContact = workSheet.Cells[rowIterator, 4].Value.ToString().FirstOrDefault();
                        user.StudentEmail = workSheet.Cells[rowIterator, 5].Value.ToString();
                        user.StudentDob = workSheet.Cells[rowIterator, 6].Value.ToString();
                        user.FirstLogin = workSheet.Cells[rowIterator, 7].Value.ToString();
                        usersList.Add(user);
                    }
                }
            }
        }
        return View("Index");
    }

这是我的模特

public partial class Student
{
    public int StudentId { get; set; }
    public string StudentNric { get; set; }
    public string StudentName { get; set; }
    public int StudentContact { get; set; }
    public string StudentEmail { get; set; }
    public DateTime StudentDob { get; set; }
    public string FirstLogin { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您必须将您在单元格中收到的字符串显式转换为 DateTime 类型,可能使用与Excel文件格式匹配的格式字符串。例如,如果excel中的日期类似于 2017-07-18 ,则必须执行

user.StudentDob = DateTime.ParseExact(
                                      workSheet.Cells[rowIterator, 6].Value.ToString(),
                                      "yyyy-MM-dd",
                                      CultureInfo.InvariantCulture);