我在excel中有一些日期字段,格式如下: 2016年1月4日,2016年2月14日等 当我尝试在数据库中插入这些字段时,我收到一个错误: 字符串未被识别为有效的DateTime
这是我的代码:
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);
但是那不起作用,因为,我认为因为我的日期不是唯一的数字格式。
答案 0 :(得分:2)
您需要解析指定要解析的日期输入格式的日期。
DateTime.ParseExact("1/4/2016", "d/M/yyyy);