使用Oledb导入Excel数据

本文关键字:数据 Excel 导入 Oledb 使用 | 更新日期: 2023-09-27 18:14:29

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

使用Oledb导入Excel数据

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

移动到conn.Open();

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