2010-05-16 6 views
1

C#과 OleDB (12.0)로 Excel 파일을 읽었습니다. 거기서 내가 읽고 싶은 시트의 이름으로 select 문을 지정해야만합니다 ([Sheet1$]).C#으로 Excel 파일 읽기 - 시트 선택

this.dataAdapter = 
    new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString); 

이름에 관계없이 첫 번째 시트를 선택할 수 있습니까?

감사합니다.

답변

5

위해 시트 이름 목록을 얻는 방법에 대한이 답변을 참조하십시오 : Using Excel OleDb to get sheet names IN SHEET ORDER

을 그리고 여기가 좀 짧은있는 내 버전입니다 :

public static IEnumerable<string> GetExcelSheetNames(string excelFile) 
{ 
    var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
      "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;"; 
    using (var connection = new OleDbConnection(connectionString)) 
    { 
     connection.Open(); 
     using (var dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null)) 
     { 
      return (dt ?? new DataTable()) 
       .Rows 
       .Cast<DataRow>() 
       .Select(row => row["TABLE_NAME"].ToString()); 
     } 
    } 
} 
+0

이 작동하지만,이처럼 보인다 알고 있어야 그것도 그냥 시트보다 다른 것들을 반환하므로 필터링 할 수 있습니다 (나는 지금 기억할 수는 없지만 이름이 범위라고 생각하거나 목록에있는 것과 같다고 생각합니다). –

+0

감사합니다. BTW "Extended Properties = Excel 8.0"은 xlsx를 열지 않고 "Extended Properties = Excel 12.0"을 사용해야합니다. –