2

I am exporting the result from a database to excel using ExcelPackage(EPPLUS nuget package). The datetime field from the database is in string and in the format - yyyyMMddhhmmssfff which is not readable in excel after exporting-ex- 20191211034422455. So i need to convert this to readable format like DD-MM-YYYY HH:MM or any other readable format. How do i achieve it. Do i need to parse each row and convert explicitly? And for conversion, do i have to first convert it to datetime and then to string again?

My current code Snippet

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

Any help would be greatly appreciated. Also is there a possibility that may be i can just convert it to DateTime and export as DateTime instead of string to datetime and again to string before exporting

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
230490
  • 516
  • 4
  • 15
  • Are you sure you're storing these values as strings in your database? Good database design would store them as DateTime (or equivalent) objects. – ProgrammingLlama Dec 16 '19 at 08:03
  • Yes, its been stored as string. Not sure why this was decided as this database exists from beginning – 230490 Dec 16 '19 at 08:05
  • Don't use strings, use dates and set the correct date style instead. Modifying the cell value doesn't change how it's formatted. It can make Excel treat that value as a string instead of a date though, breaking any date-related formulas – Panagiotis Kanavos Dec 16 '19 at 08:19
  • PS: You don't to load a DataTable, you can use LoadFromDataReader. Even if you want a DataTable, you don't need SqlDataAdapter to do it – Panagiotis Kanavos Dec 16 '19 at 08:22

1 Answers1

3

You Should convert it to DateTime and then to string again.

In case you got a DateTime having milliseconds, use the following formatting (Link live demo here)

string format = "yyyyMMddHHmmssfff";
string dateTime = "20191211034422455";
var x = DateTime.ParseExact(dateTime, format, CultureInfo.InvariantCulture);
var result = x.ToString("dd-MM-yyyy HH:MM"); // In my opinion, You just convert to Date to use instead of then to string like this.
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56