用C#怎么读取excle表的工作薄名?求几句代码?

2022-07-31 科技 51阅读
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" +
Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);

conn.Open();

//返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等
DataTable dtSheetName = conn.GetOleDbSchemaTable (
OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

//包含excel中表名的字符串数组
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}

OleDbDataAdapter myCommand = null;
DataTable dt = new DataTable();

//从指定的表明查询数据,可先把所有表明列出来供用户选择
string strExcel = "select * from [" + strTableNames[0] + "]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
dt = new DataTable();
myCommand.Fill(dt);

dataGridView1.DataSource = dt; //绑定到界面
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com