Excel Reader(为sheet1 $设置常规变量)

时间:2018-07-08 23:10:04

标签: c# excel

关于this thread,我想知道是否可以从excel文件中读取任何内容,而不必设置要读取的应用程序,例如Sheet1 }},而是使用某种表示第一张纸的变量

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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;
        }
    }
}