简体   繁体   中英

C# DateTime Format issue in Excel

I am formating my datetime column based on the culture (en-GB), which is fetched from my database. And I am exporting this data to excel. When I download my data some datetime's are displayed like this "16/10/2013 16:34:14" (ie, 24 Hours) which is correct and others are displayed like this "11/10/2013 12:47:01 PM" (ie, 12 Hours) which is wrong. For en-GB the datetime format should be "dd/MM/yyyy HH:mm:ss". How to solve this issue. Kindly advice me. Thanks in advance.

Below is the code which i used to export the data to Excel.

GridView gv = new GridView();
gv.DataSource = dtTemp; // Here is My data 
gv.DataBind();

Response.Clear();

// 'set the response mime type for excel
string fileName = string.Empty;
fileName = "Online_Topup_Report_" + DateTime.Now.Date.ToString(DayFormat.Value.ToString().Replace("/", "-")).ToString() + ".xls";
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "");
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.Charset = "UTF-8";
StringWriter stringWrite = new StringWriter();
// 'create an htmltextwriter which uses the stringwriter
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);

// 'tell the datagrid to render itself to our htmltextwriter
gv.RenderControl(htmlWrite);
Response.Output.Write(stringWrite.ToString());
Response.End();

You should format first datetime whatever you are getting from Database to format: "dd/MM/yyyy HH:mm:ss"

and then you can export it to excel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM