将数据从Excel导入到MVC

拉米·奥斯曼|

我试图通过MVC从Excel到SQL检索数据,但是日期时间字段出现问题,因为它出现以下错误:

无法将类型'string'隐式转换为'System.DateTime?'


X

我在控制器中的代码:

public static string ConvertDateTime(string data)
    {
        DateTime dateTime;
        return DateTime.TryParseExact(data, "mm/dd/yy hh:mm"
            , System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)
            ? dateTime.ToString("mm/dd/yy hh:mm") : "N/A";
    }

    [HttpPost]
    public ActionResult MultipleUpload(HttpPostedFileBase Excelfile)
    {
                string path = Server.MapPath("~/Content/" + Excelfile.FileName);
                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
                Excelfile.SaveAs(path);
                //
                Excel.Application application = new Excel.Application();
                Excel.Workbook workbook = application.Workbooks.Open(path);
                Excel.Worksheet worksheet = workbook.ActiveSheet;
                Excel.Range range = worksheet.UsedRange;
                List<goldenfpcmap> map = new List<goldenfpcmap>();
                for (int row = 1; row <= range.Rows.Count; row++)
                {
                    goldenfpcmap m = new goldenfpcmap();
                    m.InputDate = ConvertDateTime(((Excel.Range)range.Cells[row, 7]).Value.ToString());
                    db.goldenfpcmaps.Add(m);
                    db.SaveChanges();
                }
                return RedirectToAction("Action");
    }
derloopkat

对于初学者,DateTime格式模式“ mm”代表分钟,而月份则是“ MM”。因此,您可能不是说“ mm / dd / yy hh:mm”,而是“ MM / dd / yy hh:mm”。

其次,您报告的错误表明属性或字段m.InputDate在预期中,DateTime?但正在获取字符串。我建议重构您的convert方法。

public static DateTime? ConvertDateTime(string data)
{
    DateTime dateTime;
    if (DateTime.TryParseExact(data, "MM/dd/yy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
        return dateTime;
    else
        return null;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章