如何将Excel列名称转换为C#组合框?

时间:2014-01-30 07:33:15

标签: c# excel vba

您好我正在尝试从PC中的任何位置获取Excel工作表,每当有人浏览并选择Excel工作表时,我希望其列名在组合框中列出。到目前为止,我已经编码了困难的部分,我仍然得到一个小错误说 " Microsoft Access数据库引擎找不到对象'列'。确保对象存在,并且您正确拼写其名称和路径名称。如果'列'不是本地对象,请检查您的网络连接或联系服务器管理员" 但我已成功在sql server数据库上实现相同的代码。只有当我尝试访问Excel工作表时才会出现此错误。为什么会出现这个错误以及如何修复它?谢谢。

    private String openfile()
    {

        string tempPath = "";
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "open MSexcel file ";
        fDialog.Filter = "All Files(*.*)|*.*";
        fDialog.InitialDirectory = @"C:\";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {

              tempPath = fDialog.FileName;
              return tempPath;

        }
        return null;
    }

    private void openpath(string path)
    {

        newconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source="
                   + Convert.ToString(path) + ";Extended Properties=\"Excel 12.0;HDR={1}\";");




    }

    private void loadtolist()
    {
        newconn.Open();
        cmb.Items.Clear(); //cmb is combo box name
        newcmd = new OleDbCommand();
        newcmd.Connection = newconn;
        newcmd.CommandType = CommandType.Text;
        newcmd.CommandText = "SELECT column_name from information_schema.columns where table_name = 'BigData' Order by ordinal_position";

        dr = newcmd.ExecuteReader();
        if (dr.HasRows)

        {
            while (dr.Read())
            {
                cmb.Items.Add(dr[0].ToString());
            }

        }
        dr.Close();
        newconn.Close();
    }

1 个答案:

答案 0 :(得分:0)

尝试一下..

    string connectionString = string.Format(Thread.CurrentThread.CurrentCulture, "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;'", excelFilePath);
    DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
    using (DbConnection connection = factory.CreateConnection())
    {
        connection.ConnectionString = connectionString;
        using (DbCommand command = connection.CreateCommand())
        {
            command.CommandText = @"SELECT [File], [ItemName], [ItemDescription], [Photographer name], [Date], [Environment site] FROM [Metadata$]";
            connection.Open();
            using (DbDataReader dr = command.ExecuteReader())
            {
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        .......
                    }
                }
            }
            connection.Close();
        }
    }