C# :excel读取表名,这样获取的表名不会出错

本文介绍了一种从Excel文件(.xls和.xlsx)中提取有效表名的方法,并通过过滤处理确保表名的正确性。该方法使用ADO.NET OleDB连接到Excel文件并获取其架构表,进而提取所有工作表的名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对获取的表名进行了过滤处理,提取出有效的表名,放到string[]中,应用的时候需要加上$符号,比如

本来:“select * from [sheet1$]”

获得表名后string[] excelNames 需要 如对第一个表名:"select * from"+" ["+excelNames[0]+"$"+"]"(跟原来的形式相同)


 private String[] GetExcelSheetNames(string fileName)  
{  
    OleDbConnection objConn = null;  
    System.Data.DataTable dt = null;  
    try  
    {  
        string connString=string.Empty;  
        string FileType =fileName.Substring(fileName.LastIndexOf("."));  
        if (FileType == ".xls")    
         connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +  
            "Data Source=" + fileName + ";Extended Properties=Excel 8.0;";  
        else//.xlsx   
            connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";    
        // 创建连接对象    
        objConn = new OleDbConnection(connString);  
        // 打开数据库连接    
       objConn.Open();  
        // 得到包含数据架构的数据表    
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
        if (dt == null)  
        {  
            return null;  
        }  
        String[] excelSheets = new String[dt.Rows.Count];  
        int i = 0;  
        // 添加工作表名称到字符串数组    
        foreach (DataRow row in dt.Rows)  
        {  
            string strSheetTableName = row["TABLE_NAME"].ToString();  
           //过滤无效SheetName   
            if (strSheetTableName.Contains("$")&&strSheetTableName.Replace("'", "").EndsWith("$"))  
            {  
                excelSheets[i] = strSheetTableName.Substring(0, strSheetTableName.Length - 1);//提取有效的sheet值
                //MessageBox.Show(excelSheets[i]);
		i++;
            }                     
            //i++; //放在这里是错误的, 
        }  
        return excelSheets;  
    }  
    catch (Exception ex)  
    {  
        MessageBox.Show(ex.ToString());  
        return null;  
    }  
    finally  
    {  
        // 清理    
        if (objConn != null)  
        {  
            objConn.Close();  
            objConn.Dispose();  
        }  
        if (dt != null)  
        {  
            dt.Dispose();  
        }  
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值