.net导入excel时获取第一个Sheet名称

作者:袖梨 2022-06-25

///


/// 根据excel的文件的路径提取其中表的数据
///

/// excel文件的路径
private void getdatafromexcelwithappointsheetname(string path)
        {
            //连接串
            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; //绑定到界面
        }

相关文章

精彩推荐