IExcelReader如何读取date并将其插入到sql?

我在我的Excel中有一些date字段是这样的格式:1/4/2016,2/14/2016等。当我尝试在数据库中插入字段,我得到一个错误:string不被认定为有效约会时间

这是我的代码:

IExcelDataReader excelReader; if (System.IO.Path.GetExtension(ope.FileName).ToUpper() == ".XLS") { excelReader = ExcelReaderFactory.CreateBinaryReader(stream,true); } else { excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } excelReader.IsFirstRowAsColumnNames = true; DataSet result = excelReader.AsDataSet(true); DataClassesFinPodaciDataContext conn = new DataClassesFinPodaciDataContext(); foreach (DataRow dr in result.Tables[0].Rows) { string s1 = Convert.ToString(dr[4]); DateTime conv1 = Convert.ToDateTime(s1); string d2 = Convert.ToString(dr[14]); DateTime conv2 = Convert.ToDateTime(d2); string d3 = Convert.ToString(dr[15]); DateTime conv3 = Convert.ToDateTime(d3); string d4 = Convert.ToString(dr[19]); DateTime conv4 = Convert.ToDateTime(d4); //string d1 = string.Parse() tblFinansijskiPodaci addTable = new tblFinansijskiPodaci() { Firma = Convert.ToInt32(dr[0]), NazFirme = Convert.ToString(dr[1]), VrstaNal = Convert.ToString(dr[2]), BrojNal = Convert.ToInt32(dr[3]), DatumNal = conv1, SifraRJ = Convert.ToInt32(dr[5]), Konto = Convert.ToString(dr[6]), NazivKonta = Convert.ToString(dr[7]), Partner = Convert.ToInt32(dr[8]), NazivPartnera = Convert.ToString(dr[9]), Adresa = Convert.ToString(dr[10]), Mesto = Convert.ToString(dr[11]), PIB = Convert.ToString(dr[12]), BrojDok = Convert.ToString(dr[13]), DatumDok = conv2, DatumVal = conv3, Opis = Convert.ToString(dr[16]), Duguje = Convert.ToInt32(dr[17]), Potrazuje = Convert.ToInt32(dr[18]), DatumZaPDV = conv4, Valuta = Convert.ToString(dr[20]), DevDuguje = Convert.ToInt32(dr[21]), DevPotrazuje = Convert.ToInt32(dr[22]), Oslob = Convert.ToInt32(dr[23]), IznosPDV = Convert.ToInt32(dr[24]), Oslob1 = Convert.ToInt32(dr[25]), IznosOslob = Convert.ToInt32(dr[26]), UvozOsnovica = Convert.ToInt32(dr[27]) }; // conn.ExecuteCommand("TRUNCATE TABLE Excel"); // conn.ExecuteCommand("DELETE FROM tblFinansijskiPodaci where ime='a'"); conn.tblFinansijskiPodacis.InsertOnSubmit(addTable); } conn.SubmitChanges(); excelReader.Close(); 

我也试过了

 double d = double.Parse(Convert.ToString(dr[4])); DateTime conv = DateTime.FromOADate(d); 

但没有工作,因为我觉得我的date不是唯一的数字格式。

您需要parsing指定要parsing的date的input格式的date。

 DateTime.ParseExact("1/4/2016", "d/M/yyyy);