【问题标题】:Importing data from Excel to MVC将数据从 Excel 导入 MVC
【发布时间】:2018-12-15 21:49:41
【问题描述】:

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

无法将类型“字符串”隐式转换为“System.DateTime?”


我的控制器中的代码:

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");
    }

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

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

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

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;
}

【讨论】:

  • 谢谢,mm 几个月是错字
猜你喜欢
  • 2017-03-24
  • 2010-12-07
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多