2011-03-29 152 views
1

我必須檢索數據表格數據庫到word文檔和excel工作表,但我可以做excel表&不適用於ms word或pdf。任何人都可以告訴我該怎麼做? 這裏是我在.net中的代碼:如何從數據庫檢索數據到word文檔。淨

protected void btnExportToExcel_Click(object sender, EventArgs e) 
    { 
     Response.Clear(); 
     Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.xls"); 
     Response.Charset = ""; 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.ContentType = "application/vnd.ms-excel"; 
     System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 
     System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); 
     GridView1.RenderControl(htmlWrite); 
     Response.Write(stringWrite.ToString()); 
     Response.End(); 
    } 
    protected void btnExportToWord_Click(object sender, EventArgs e) 
    { 
     Response.Clear(); 
     Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.docx"); 
     Response.Charset = ""; 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.ContentType = "application/vnd.ms-word"; 
     System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 
     System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); 
     GridView1.RenderControl(htmlWrite); 
     Response.Write(stringWrite.ToString()); 
     Response.End(); 
    } 

回答

0

好吧。你的代碼似乎在我的最後工作。您在出口時是否收到任何異常情況?我前一段時間也收到了同樣的東西。

我剛剛在aspx頁面的Page指令中創建了EnableEventValidation =「false」,它工作正常。你可以嘗試一樣的。 它應該工作。

0

嘗試將內容類型更改爲 Response.AppendHeader(「Content-Type」,「application/msword」); 還確保您是否使用「css」樣式將樣式包含在要呈現的字符串中。