Home » excel » c# – How to restrict excel from taking its default time format

c# – How to restrict excel from taking its default time format

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am exporting data to excel sheet. I have a field called totalWorkingHours as string which holds the hours and minutes as “hh:mm” e.g. “119:20”. However excel reads this as a timestamp and adds seconds to it: “119:20:00”. I want to remove the seconds and the value should be displayed as “119:20” only.

Following code returns the Memory Stream which is then exported to excel:

   public static MemoryStream GetCSV(string[] fieldsToExpose, DataTable data)
   {
       MemoryStream stream = new MemoryStream();

       using (var writer = new StreamWriter(stream))
       {
           for (int i = 0; i < fieldsToExpose.Length; i++)
           {
               if (i != 0) { writer.Write(","); }
               writer.Write("\"");
               writer.Write(fieldsToExpose[i].Replace("\"", "\"\""));
               writer.Write("\"");
           }
           writer.Write("\n");

           foreach (DataRow row in data.Rows)
           {
               for (int i = 0; i < fieldsToExpose.Length; i++)
               {
                   if (i != 0) { writer.Write(","); }
                   writer.Write("\"");

                   if (row[fieldsToExpose[i]].GetType() == typeof(DateTime))
                   {
                       var Val = (DateTime)row[fieldsToExpose[i]];
                       string output = Val.ToString("dd-MMM-yyyy hh:mm");
                       if (Val.TimeOfDay == new TimeSpan(0, 0, 0))
                       {
                           output = Val.ToString("dd-MMM-yyyy");
                       }
                       writer.Write(output.Replace("\"", "\"\""));
                   }
                   else
                   {
                       writer.Write(row[fieldsToExpose[i]].ToString().Replace("\"", "\"\""));
                   }
                   writer.Write("\"");
               }
               writer.Write("\n");
           }
       }
       return stream;
   }

U can see the value coming here

Here, how it looks in excel

How to&Answers:

I think the good solution for this would be that you add one space before your string e.g ‘ 110:20’, this will work and excel would read it in string format and will not convert it to date format. hope you get the solution