使用Oledb导入Excel数据

时间:2013-05-19 05:33:53

标签: c# excel oledb

我使用以下代码使用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();
    }
}

1 个答案:

答案 0 :(得分:0)

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

将其移至conn.Open();

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