2013-12-12 49 views
0

我產生在ASP.Net Excel文件與下面的代碼:導出數據表爲Excel格式/擴展程序錯誤

if (dataTable.Rows.Count > 0) 
{ 
    var tw = new StringWriter(); 
    var hw = new System.Web.UI.HtmlTextWriter(tw); 
    var dgGrid = new DataGrid(); 
    dgGrid.DataSource = dataTable; 
    dgGrid.DataBind(); 
    dgGrid.RenderControl(hw); 

    attachment = "attachment; filename=" + fileName + ".xls"; 

    Response.Charset = "UTF-8"; 
    Response.ContentType = "application/vnd.ms-excel"; 
    Response.AppendHeader("content-disposition", attachment); 
    outputResponse = tw.ToString(); 
} 

但是,當我想打開Excel文檔提示錯誤:

Error: excel cannot open the file .xls because the file format or file extension is not valid

如何我可以解決嗎?

+0

你有沒有嘗試過它'Response.Charset =「UTF-8」;'? – Koen

+0

是的,我第一次嘗試沒有字符集,然後我得到錯誤,然後我嘗試使用字符集,並再次出現錯誤。 – UserStackk

回答

0

要麼使用對Excel應用程序對象的引用來創建實際的Excel文件,請使用許多基於codeplex的項目之一來創建Excel電子表格,或者最容易地從您的數據網格創建CSV文件並返回該文件,電腦會提示他們在Excel中打開。

0

只是想你的代碼,到最後一行,我已經改變了異常:

var tw = new StringWriter(); 
    var hw = new System.Web.UI.HtmlTextWriter(tw); 
    var dgGrid = new DataGrid(); 
    dgGrid.DataSource = dataTable; 
    dgGrid.DataBind(); 
    dgGrid.RenderControl(hw); 

    var attachment = "attachment; filename=" + fileName + ".xls"; 

    Response.Charset = "UTF-8"; 
    Response.ContentType = "application/vnd.ms-excel"; 
    Response.AppendHeader("content-disposition", attachment); 
    // outputResponse = tw.ToString(); 
    Response.Output.Write(tw.ToString()); 
    Response.Flush(); 
    Response.End(); 

我的數據表是簡單的數據(字母和數字)2山坳表,它被打開這應該。

你會得到寫着消息:

The file you are trying to open'yourfilename.xls', is in a different format thahn 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?

點擊OK後打開該文件就好了。