2013-05-19 62 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