Getting the first sheet from an Excel document regardless of sheet name with OleDb

前端 未结 9 625
青春惊慌失措
青春惊慌失措 2020-12-29 02:23

I have users that name their sheets all sorts of crazy things, but I want to be able to get the first sheet of the Excel document regardless of what it is named.

I

相关标签:
9条回答
  • 2020-12-29 02:32
    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();
    
    0 讨论(0)
  • Basically a copy of Anirudh Gaur's answer. I did some reformatting of the code and put it into a function. I added a StringBuilder so I can do more with the SELECT statement.

    Upvotes go to 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
    
    0 讨论(0)
  • 2020-12-29 02:33

    You can use this approach also for getting sheet name. See comments for more understanding

    myExcelConn.Open()
    
    //GET DATA FROM EXCEL SHEET.
    Dim str As String = String.Empty
    Dim Sheets As DataTable = myExcelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
    For i As Integer = 0 To Sheets.Rows.Count - 1
        str += Sheets.Rows(i)("TABLE_NAME").ToString() + "," //It will return sheet1,sheet2,sheet3 according to my excel file
    Next
    
    Dim objOleDB As New OleDbCommand("SELECT *FROM [" + str.Split(",")(0) + "]", myExcelConn) //It will select sheet1
    Me.Label1.Text = str.Split(",")(0).Replace("$", "")
    // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
    Dim objBulkReader As OleDbDataReader
    objBulkReader = objOleDB.ExecuteReader
    
    Dim dt As DataTable = New DataTable
    dt.Load(objBulkReader)
    
    //FINALLY, BIND THE EXTRACTED DATA TO THE GRIDVIEW.
    GridView1.DataSource = dt
    GridView1.DataBind()
    //If you want sheet2 data
     Dim objOleDB1 As New OleDbCommand("SELECT *FROM [" + str.Split(",")(1).Split(",")(0) + "]", myExcelConn)
    //If you want sheet3 data
     Dim objOleDB2 As New OleDbCommand("SELECT *FROM [" + str.Split(",")(2).Split(",")(0) + "]", myExcelConn)
    
    0 讨论(0)
  • 2020-12-29 02:33

    You can get sheet1 name like this and use in this manner.If you want to get other sheet names you can increase value from 0,1,2..

     Dim myExcelConn As OleDbConnection = _
                    New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
                        Server.MapPath(".") & "\" & FileUpload1.FileName() & _
                        ";Extended Properties=Excel 12.0;")
        Dim Sheets As DataTable = myExcelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
                    Sheet1 = Sheets.Rows(0)("TABLE_NAME").ToString()
      Dim objOleDB As New OleDbCommand("SELECT *FROM [" + Sheet1 + "]", myExcelConn)
    
    0 讨论(0)
  • 2020-12-29 02:35

    This code has worked fine where i have used the data grid "DataGridView1" to load all the content of the sheet

    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()
    
    0 讨论(0)
  • 2020-12-29 02:35

    That's my solution

     private static string GetExcelWorkSheet(string pathToExcelFile)
            {
                Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
    
                Microsoft.Office.Interop.Excel.Workbook theWorkbook = null;
    
                theWorkbook = ExcelObj.Workbooks.Open(pathToExcelFile);
    
                Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
    
                // Get the reference of first worksheet. Index start at 1 
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
    
                // Get the name of worksheet.
                string strWorksheetName = worksheet.Name; 
    
                return strWorksheetName;
            }
    
    0 讨论(0)
提交回复
热议问题