停止date自动格式从C#中从DataGrid导出到Excel时

我目前格式化一个特定的Excel文件从DataSet / DataGrid导出的date。
date格式如下:

DateTime date = Convert.ToDateTime(entry.Date); string formatdate = String.Format("{0:yyyy/MM/dd}", date); 

一旦创build完DataSet,我使用下面的代码将DataSet导出到Excel文件中:

 public static void ExportDStoExcel(DataSet ds, string filename) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Charset = ""; response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[0]; dg.DataBind(); dg.RenderControl(htw); response.Write(sw.ToString()); response.End(); } } } 

我唯一的问题是,一旦我将它导出到Excel,Excel将自动格式化date,如下所示:MM / DD / YYYY而不是YYYY / MM / DD。

我知道这可以通过在Excel中打开手动实现,但导出正在构build到自动化系统中,需要进行硬编码。

有没有办法绕过Excel的DateTime自动格式?

现在你只是输出HTML表格,Excel解释它的喜好。 你可以自己调整到Excel的级别,以便能够指定列的属性(将types设置为文本而不是常规)。 这意味着你需要生成实际的xls文件(这里有各种各样的库)。 或者(如果限制到Office 2010是可以接受的)以Open XML格式获得,您可以使用常规的.NET API编写。

我遇到了同样的问题,并通过在文本前添加一个不间断的空格(&nbsp)来解决此问题。 从自动格式化停止Excel。 不是最干净的解决scheme,但为我做了诡计…

你可以使用mso-number-format来deviseexcel单元格

mso-number-format:"\\@"

\@将告诉excel只处理文本格式的所有数据。 所以自动格式不会发生。

请更新您的代码,如下所示:

 response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">"); response.Write("<head><style> td {mso-number-format:\\@;} </style></head><body>"); using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[0]; dg.DataBind(); dg.RenderControl(htw); response.Write(sw.ToString()); response.Write("</body></html>"); response.End(); } } 

要么

你也可以尝试使用特定的date格式。 请参阅: http : //cosicimiento.blogspot.in/2008/11/styling-excel-cells-with-mso-number.html

mso-number-format:"yyyy\/mm\/dd"