2010-12-10 64 views
1

我正在格式化某個特定Excel文件的日期從DataSet/DataGrid導出。
日期被格式化,像這樣:停止日期在從DataGrid導出到Excel中的Excel時自動格式化#

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

一旦創建了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將自動格式化日期,如下所示:MM/DD/YYYY而不是YYYY/MM/DD。

我知道這可以通過在Excel中打開來手動實現,但導出內置到自動系統中,需要進行硬編碼。

有沒有辦法繞過Excel的DateTime自動格式?

回答

1

現在你只是輸出HTML表格,Excel解釋它的喜好。你可以自己調整到Excel的級別,以便能夠指定列的屬性(將類型設置爲文本而不是常規)。 這意味着你需要生成實際的xls文件(這裏有各種各樣的庫)。或者(如果限制到Office 2010是可以接受的)以Open XML格式獲得,您可以使用常規的.NET API編寫該格式。

+0

去使用微軟的開放的XML SDK 2.0去打開XML路線,它看起來像它應該做的伎倆!感謝您指點我正確的方向! – Lando 2010-12-13 23:29:58

3

我有同樣的問題,並通過在文本前添加一個不間斷的空格(& nbsp)來解決它。從自動格式化中停止Excel。不乾淨的解決方案,但沒有的伎倆我...

0

可以練成的風格與MSO的數字格式細胞

mso-number-format:"\\@"

\@會告訴擅長治療以純文本格式的所有數據。所以自動格式不會發生。

請更新您這樣的代碼:

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

OR

您可以使用特定的日期格式嘗試也。 參見:http://cosicimiento.blogspot.in/2008/11/styling-excel-cells-with-mso-number.html

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