2011-05-23 50 views
2

在我的asp.net web應用程序中有一個要求,我必須從excel中導入和導出數據。我該怎麼做?如何在ASP.NET中導入導出爲Excel功能?

+0

導入數據您是否想要導出到Excel 2003,2007,或2010? OleDb噴氣機版本因Excel的每個版本而異。 – bitxwise 2011-05-23 07:09:45

+0

您有45個問題,您還沒有投票。 – 2011-06-22 13:28:35

回答

0

這裏是代碼,數據導出Excel中

StringWriter sw = new StringWriter(); 
    HtmlTextWriter htw = new HtmlTextWriter(sw); 
    string attachment = "attachment; filename=excel" + ".xls"; 
    Response.ClearContent(); 
    Response.AddHeader("content-disposition", attachment); 
    rptMain.DataBind(); 
    rptMain.RenderControl(htw); 
    Response.Write(sw.ToString()); 
    Response.Flush(); 
    Response.End(); 

,這裏是代碼從Excel

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); 
     DbDataAdapter adapter = factory.CreateDataAdapter(); 
     DbCommand selectCommand = factory.CreateCommand(); 
     selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]"; 
     DbConnection connection = factory.CreateConnection(); 
     connection.ConnectionString = connectionString; 
     selectCommand.Connection = connection; 
     adapter.SelectCommand = selectCommand; 
     DataTable dtbl = new DataTable(); 
     adapter.Fill(dtbl); 

     if (dtbl.Rows.Count > 0) 
     { 
     ............. 
     ............. 
     }