2009-09-17 19 views
26

Ho utenti che nominano i loro fogli ogni sorta di cose pazze, ma voglio essere in grado di ottenere il primo foglio del documento Excel indipendentemente da cosa sia di nome.Ottenere il primo foglio da un documento Excel indipendentemente dal nome del foglio con OleDb

Attualmente uso:

OleDbDataAdapter adapter = new OleDbDataAdapter(
"SELECT * FROM [sheetName$]", connString); 

Come potrei fare per ottenere il primo foglio non importa quello che prende il nome?

Grazie.

+1

possibile duplicato del [Utilizzo di Excel OleDb per ottenere i nomi dei fogli in lamiera di ordine] (http://stackoverflow.com/questions/1164698/using-excel-oledb-to -get-sheet-names-in-sheet-order) –

risposta

26

finito per usare questo:

using (OleDbConnection conn = new OleDbConnection(connString)) 
{ 
    conn.Open(); 
    dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); 
    Sheet1= dtSchema.Rows[0].Field<string>("TABLE_NAME"); 
} 
+1

Dopo tutte le mie ricerche, questo bel frammento è stato ciò che ha risolto per me. – PhilNicholas

1

È possibile utilizzare GetOleDbSchemaTable (VB) o GetOleDbSchemaTable (C#).

Utilizzo delle tabelle Enum restituirà un elenco di tutti i nomi dei fogli di lavoro, che è possibile utilizzare per creare dinamicamente l'SQL richiesto.

È possibile utilizzare:

MySchemaTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})

Tutti i nomi fogli di lavoro verranno restituiti come parte di un DataTable è possibile itterate attraverso.

Utilizzando le informazioni OleDbSchemaGuid possono essere recuperate sul

  • Colonne
  • chiavi esterne
  • indici
  • chiavi primarie
  • Tabelle
  • Visualizzazioni

completa MSDN documentazione disponibile here

+0

sembra che restituisca un datatable, come posso ottenere il nome del foglio? è un campo chiamato? – naspinski

+0

Inoltre, quali parametri devo passare per le restrizioni: Oggetto []? – naspinski

+0

@naspinski - Gli articoli che ho linkato contengono tutte le informazioni richieste. Non ho lavorato con OLEDB negli ultimi 2 anni. Se ricordo correttamente il nome della tabella sarà nel campo COLUMN_NAME. – BinaryMisfit

13
OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="Path"; Extended Properties=Excel 12.0;Persist Security Info=False;"); 

oconn.Open(); 
myCommand.Connection = oconn; 
DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
if (dbSchema == null || dbSchema.Rows.Count < 1) 
{ 
    throw new Exception("Error: Could not determine the name of the first worksheet."); 
} 
string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString(); 
+1

In base ai miei test, restituisce il primo foglio _alfabetico_, non il primo foglio in base all'ordine in cui vengono visualizzati nella cartella di lavoro (da sinistra a destra). – Doppelganger

3

Questo codice ha funzionato benissimo in cui ho usato la griglia di dati "DataGridView1" per caricare tutto il contenuto del il foglio

Dim MyConnection As System.Data.OleDb.OleDbConnection 
Dim DtSet As System.Data.DataSet : Dim filteext As String = "" 

''check for the file type 
If IO.Path.GetExtension(fileName) = "xls" Then 
       filteext = "Excel 8.0" 
ElseIf IO.Path.GetExtension(fileName) = ".xlsx" Then 
       filteext = "Excel 12.0" 
End If 

''open connection 

MyConnection = New System.Data.OleDb.OleDbConnection _ 
       ("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileName & "';Extended Properties=" & filteext & ";") 
      MyConnection.Open() 

    Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME") 

    Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", myTableName), MyConnection) 


    MyCommand.TableMappings.Add("Table", "TestTable") 
      DtSet = New System.Data.DataSet 

    MyCommand.Fill(DtSet) 

    DataGridView1.DataSource = DtSet.Tables(0) 
      'DtSet.DataSetName. 

    MyConnection.Close() 
1

Fondamentalmente una copia di Anirudh Gau la risposta di r. Ho fatto alcune riformattazioni del codice e l'ho messo in una funzione. Ho aggiunto un StringBuilder in modo da poter fare di più con l'istruzione SELECT.

upvotes andare a Anirudh Gaur

Private Function Load_XLS(FileName As String) As DataTable 
    Dim DataTable As New DataTable 
    Dim Format As String = "" 
    If IO.Path.GetExtension(FileName) = ".xls" Then 
     Format = "Excel 8.0" 
    ElseIf IO.Path.GetExtension(FileName) = ".xlsx" Then 
     Format = "Excel 12.0" 
    End If 

    Using Connection As New OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & FileName & "';Extended Properties=" & Format & ";") 
     Connection.Open() 

     Dim TableName As String = Connection.GetSchema("Tables").Rows(0)("TABLE_NAME") 

     Dim SQLCommand As New Text.StringBuilder 
     SQLCommand.AppendLine("SELECT *") 
     SQLCommand.AppendLine("FROM [{0}]") 

     Dim Command As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(String.Format(SQLCommand.ToString, TableName), Connection) 

     Command.Fill(DataTable) 

     Connection.Close() 
    End Using 
    Return DataTable 
End Function 
Problemi correlati