C# Excel阅读器(为sheet1$设置常规变量)

C# Excel阅读器(为sheet1$设置常规变量),c#,excel,C#,Excel,关于,我想知道是否有任何方法可以从excel文件中读取,而不必设置要读取的应用程序,例如Sheet1,例如OleDbCommand sqlCommand=new-OleDbCommandSELECT*from[Sheet1$],conObj;而是使用某种表示第一张图纸的变量使用字符串插值将变量注入db命令: var sheetNo = "Sheet1$"; OleDbCommand sqlCommand = new OleDbCommand($"SELECT * FROM [{sheetNo}

关于,我想知道是否有任何方法可以从excel文件中读取,而不必设置要读取的应用程序,例如Sheet1,例如OleDbCommand sqlCommand=new-OleDbCommandSELECT*from[Sheet1$],conObj;而是使用某种表示第一张图纸的变量

使用字符串插值将变量注入db命令:

var sheetNo = "Sheet1$";
OleDbCommand sqlCommand  = new OleDbCommand($"SELECT * FROM [{sheetNo}]",conObj);

我将工作表名称放在一个组合框中,选择一个工作表后,可以加载网格

private void GetSheets()
        {
            string strFileName = @"C:\Users\xxx\Documents\Excel\TestImport.xlsx";
            string strCon = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={strFileName};Extended Properties=""Excel 12.0;HDR=YES;""";
            DataTable dt;
            using (OleDbConnection cn = new OleDbConnection(strCon))
            {
                cn.Open();
                dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            }
            string[] exSheets = new string[dt.Rows.Count];
            int i = 0;
            foreach (DataRow row in dt.Rows)
            { 
                //Get the sheet name from the DataTable
                string strSheetName = row["TABLE_NAME"].ToString();
                exSheets[i] = strSheetName;
                i ++;
            }
            cboSheets.Items.AddRange(exSheets);
        }

        private void btnFillGrid_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            string strFileName = @"C:\Users\xxx\Documents\Excel\TestImport.xlsx";
            string  strCon  = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={strFileName};Extended Properties=""Excel 12.0;HDR=YES;""";
            using (OleDbConnection cn = new OleDbConnection(strCon))
            {

                using (OleDbCommand cmd = new OleDbCommand($"Select * From [{cboSheets.Text}];", cn))
                {
                    cn.Open();
                    using (OleDbDataReader dr = cmd.ExecuteReader())
                    {
                        dt.Load(dr);
                    }
                }
            }
            dataGridView1.DataSource = dt;
        }
    }
}

strsql=SELECT*FROM[&Worksheets1.Name&$]FROM我已签出该站点,并运行了您提供的上述代码,但它表示当前上下文中不存在工作表。您知道,我想您必须使用代码其余部分中相应的工作表集合,您的问题中缺少的所有内容。我尝试了字符串插值,但收到此错误附加信息:Microsoft Access数据库引擎找不到对象“1”。确保对象存在,并且正确拼写其名称和路径名。如果“1”不是本地对象,请检查网络连接或与服务器管理员联系。这是我在[{1}]中执行的操作OleDbCommand cmd=new OleDbCommand$SELECT*,con@Jeremy22你做了一些与答案建议不同的事情,但没有奏效。如果你试着按照答案的建议去做会怎么样?这行得通吗?@Jeremy22您不能用c命名以数字开头的变量,能否尝试命名变量sheetNo并告诉我结果是什么?@FiringSquadWitness其他信息:Microsoft Access数据库引擎找不到对象“sheetNo”。确保对象存在,并且正确拼写其名称和路径名。如果“SheetNo”不是本地对象,请检查网络连接或与服务器管理员联系。。