0

我正在使用以下代码使用 Oledb 将 Excel 数据显示到 DataGrid 中。但我收到一个错误Fill: SelectCommand.Connection property has not been initialized.

谁能告诉我我哪里出错了?

谢谢

代码:

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();
    }
}
4

1 回答 1

0

您忽略了将连接分配给命令对象。

将其移至 conn.Open(); 下方

OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", conn);
于 2013-05-19T05:36:57.210 回答