获取Excel中所有Sheet名字 - Lemon_s

时间:2024-02-29 17:55:30

获取Excel中所有Sheet名字

        #region 获取Excel表的所有Sheet名字
        
public DataTable GetExcelTableName(string pExcelFile)
        {
            
if(System.IO.File.Exists(pExcelFile))
            {
                
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + pExcelFile + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
                
//string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + pExcelFile + ";" + "Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
                OleDbConnection _excelConn=new OleDbConnection(strConn);
                
try
                {
                    _excelConn.Open();
                    DataTable _table 
= _excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    
return _table;
                }
                
catch(Exception ex)
                {
                    
throw ex;
                }
                
finally
                {
                    
if(_excelConn!=null)
                        _excelConn.Close();
                }
            }
            
else
            {
                
throw new ApplicationException("文件不存在!");
            }
        }

        
public string[] GetExcelSheets(string pFlieName)
        {
            DataTable table 
= GetExcelTableName(pFlieName);
            
int count = table.Rows.Count;
            
string[] sheetNames = new string[table.Rows.Count];
            
for (int i = 0; i < count; i++)
            {
                sheetNames[i] 
= table.Rows[i]["Table_Name"].ToString();
            }
            
return sheetNames;
        }