2012-08-08 169 views
-2

我有一個asp.net頁面,其中有一個gridview和一個按鈕。 按鈕點擊事件我已經寫了輸出gridview到excel的代碼,它工作得很好。 但是當我嘗試打開導出的Excel文件它顯示一個對話框,說:GridView導出到Excel

「你試圖打開該文件是由文件extension.Verify指定不同的格式 該文件沒有損壞 並且在打開文件之前來自可信來源「。

不僅如此,我發送了Excel文件在Gmail附件,並試圖在手機中打開它,它會打開一個HTML file.What時間可以爲了這個,我做的,因爲我的客戶端將使用移動查看郵件。

+0

你試試..?把你的代碼,你有嘗試 – 2012-08-08 10:29:40

+0

請顯示您的代碼。 – SMK 2012-08-08 10:30:03

+1

完全重複http://stackoverflow.com/questions/9799726/why-showing-error-message-while-opening-xls-file – SMK 2012-08-08 10:31:18

回答

0

當我導出到excel時,我只是創建了一個逗號分隔的文件,並給它一個excel文件擴展名。當我開始使用帶雙引號的逗號分隔時,該消息就消失了。

「一」,「二」,「三」,而不是一個,兩個,三個

1

在您的按鈕單擊事件:

 protected void btnExcel_Click(object sender, ImageClickEventArgs e) 
    { 
     //export to excel 
     Response.Clear(); 
     Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); 
     Response.Charset = ""; 

     // If you want the option to open the Excel file without saving then 
     // comment out the line below 
     // Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.ContentType = "application/vnd.xls"; 
     System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 
     System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); 
     //GV is the ID of gridview 
     GV.RenderControl(htmlWrite); 
     Response.Write(stringWrite.ToString()); 
     Response.End(); 
    } 

,並覆蓋網頁代碼這種方法的背後:

public override void VerifyRenderingInServerForm(Control control) 
{ 
    /* Confirms that an HtmlForm control is rendered for the specified ASP.NET 
     server control at run time. */ 
} 
2

我建議使用Excel文件擴展名創建實際的Excel文件,而不是CSV或HTML。

完成此操作的一個簡單方法是使用ClosedXML

爲此,請從codeplex站點下載ClosedXML.dll和DocumentFormat.OpenXml.dll,並將它們作爲參考添加到ASP.NET項目中。然後,在按鈕單擊事件中,您可以簡單地設置Excel工作簿,根據您綁定到GridView的相同DataTable創建工作表,並將工作簿文件保存在HTTP響應中。事情是這樣的:

var wb = new ClosedXML.Excel.XLWorkbook(); 
DataTable dt = GetTheDataTable(); 
dt.TableName = "This will be the worksheet name"; 

wb.Worksheets.Add(dt); 

Response.Clear(); 
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\""); 

using (var ms = new System.IO.MemoryStream()) { 
    wb.SaveAs(ms); 
    ms.WriteTo(Response.OutputStream); 
    ms.Close(); 
} 

Response.End(); 

我會用ClosedXML去了其他的替代品,因爲許可限制較少,該文件是一流的,開發商是有幫助的,友好的,並且該項目目前非常活躍。