2013-05-19 66 views
0

我正在使用以下代碼將Excel數據顯示到使用Oledb的DataGrid中。但我得到一個錯誤Fill: SelectCommand.Connection property has not been initialized.使用Oledb導入Excel數據

有人可以告訴我我哪裏出錯了嗎?

感謝

代碼:

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Data.SqlClient; 
using System.Data.OleDb; 

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\testing.xlsx;Extended Properties='Excel 12.0 Xml;HDR=Yes;IMEX=1;'"); 
     OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]"); 
     if (conn.State == System.Data.ConnectionState.Open) 
     { 
      conn.Close(); 
     } 
     conn.Open(); 
     OleDbDataAdapter adap = new OleDbDataAdapter(cmd); 
     DataSet ds = new DataSet(); 
     adap.Fill(ds); 
     this.GridView1.DataSource = ds.Tables[0].DefaultView; 
     conn.Close(); 
    } 
} 

回答

0

你忽略了分配給命令對象的連接。

將此移動到下方conn.Open();

OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", conn); 
+0

酷,,,很好的捕獲...但它只是加載空白頁而不是我的內容。我的Excel表格中有很多內容,但沒有顯示內容。 – user2398215