2010-01-12 30 views
0

我想導出我的中繼器發揮所長,這裏是我的代碼...出口中繼到excel

StringWriter sw = new StringWriter(); 
    HtmlTextWriter htw = new HtmlTextWriter(sw); 
    string attachment = "attachment; filename=file.xls"; 
    Response.ClearContent(); 
    Response.AddHeader("content-disposition", attachment); 
    Response.ContentType = "application/vnd.ms-excel"; 
    rpt.RenderControl(htw); 
    Response.Write(sw.ToString()); 
    Response.Flush(); 
    Response.End(); 

當我試圖打開文件收到此錯誤

The file you are trying to open, 'file.xls', is in a different format than specified 
by the file extension. Verify that the file is not Corrupted and is from a trusted 
source before opening the file. Do you want to open the file now? 
Yes No Help option are available 

什麼問題在我的代碼或我必須做什麼解決這個問題。 謝謝

回答

2

您正在設置內容類型爲application/vnd.ms-excel,但是當您調用RenderContents方法時,您正在響應流中發送HTML內容。您可能需要一個庫來生成Excel文件。

+0

當我點擊yes選項,則正確打開罰款和顯示數據。我從互聯網上找到很多文章,發現類似的實現。 Plz檢查這篇文章http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx –

0

嘗試包裝你的內容變成這樣:

StringBuilder sb = new StringBuilder(""); 
sb.Append("<HTML xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><HEAD>"); 
sb.Append("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">"); 
sb.Append("<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>"); 
sb.Append(title); 
sb.Append("</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </HEAD><BODY>"); 
sb.Append(content); 
sb.Append("</BODY></HTML>");