简体   繁体   English

Excel中的C#DateTime格式问题

[英]C# DateTime Format issue in Excel

I am formating my datetime column based on the culture (en-GB), which is fetched from my database. 我正在根据从数据库中获取的区域性(en-GB)格式化日期时间列。 And I am exporting this data to excel. 而且我正在将此数据导出到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. 当我下载数据时,某些日期时间将显示为正确的“ 16/10/2013 16:34:14”(即24小时),而其他日期时间将显示为“ 11/10/2013 12:47:01 PM” ”(即12小时),这是错误的。 For en-GB the datetime format should be "dd/MM/yyyy HH:mm:ss". 对于en-GB,日期时间格式应为“ 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. 下面是我用来将数据导出到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" 您应该格式化第一个日期时间,无论从数据库中获得什么格式:“ dd / MM / yyyy HH:mm:ss”

and then you can export it to excel. 然后可以将其导出到excel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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