我正在使用ExcelPackage(EPPLUS nuget包)将数据库中的结果导出到excel。数据库中的datetime字段为字符串,格式为yyyyMMddhhmmssff,在export-ex-20191211034422455后无法在excel中读取。因此,我需要将其转换为可读格式,例如DD-MM-YYYY HH:MM或任何其他可读格式。我如何实现它。我需要解析每一行并进行显式转换吗?为了进行转换,我是否必须先将其转换为日期时间,然后再次转换为字符串?
我当前的代码片段
//Method which reads data from database
using (SqlConnection sqlcon = new SqlConnection(ConnStrng))
{
sqlcon.Open();
string query = "Select Vehicleid,Speed,Datetime from VehiclDBk where Speed>30 and Datetime between '" + startDate + "' and '" + endDate + "'";
SqlDataAdapter sqlda = new SqlDataAdapter(query, sqlcon);
valRes = new DataTable();
sqlda.Fill(valRes);
DBView.DataSource = valRes;
sqlcon.Close();
}
// Method which exports data when user presses export button
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(DateTime.Now.ToShortDateString());
ws.Cells["A1"].LoadFromDataTable(valRes, true);
pck.SaveAs(new FileInfo(savefile.FileName));
}
任何帮助将不胜感激
string format = "yyyyMMddHHmmssfff";
string dateTime = "20191211034422455";
var x = DateTime.ParseExact(dateTime, format, CultureInfo.InvariantCulture);
var result = x.ToString("dd-MM-yyyy HH:MM");