在将DataTable导出到excel之前,将日期时间格式为“ yyyyMMddhhmmssfff”的字符串转换为“ DD-MM-YYYY HH:MM)

问题描述 投票:0回答:1

我正在使用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));
                        }

任何帮助将不胜感激

c# datetime datetime-format epplus excelpackage
1个回答
0
投票
如果您的DateTime有毫秒,请使用以下格式(链接实时演示here

string format = "yyyyMMddHHmmssfff"; string dateTime = "20191211034422455"; var x = DateTime.ParseExact(dateTime, format, CultureInfo.InvariantCulture); var result = x.ToString("dd-MM-yyyy HH:MM");

© www.soinside.com 2019 - 2024. All rights reserved.