Read an Excel file with ASP.net

On 18 November 2010, in ASP.net, by Himselff

For Windows 64 bits, you will need the following program to be install for the code to work :

http://www.microsoft.com/downloads/en/details.aspx?familyid=7554f536-8c28-4598-9b72-ef94e038c891&displaylang=en

        Dim connectionString As String
        Dim myFile As String
        
        myFile = "C:\FRED- Computer 2010.xlsx"
        
        'Validate wich version of excel file it is
        If InStr(myFile, "xlsx") > 0 Then
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myFile & ";Extended Properties=Excel 12.0"
        Else
            If InStr(myFile, "xls") > 0 Then
                
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myFile & ";Extended Properties=Excel 8.0"
                
            End If
        End If
        
        ' Create the connection object
        Dim oledbConn As OleDbConnection = New OleDbConnection(connectionString)
        
        ' Open connection
        oledbConn.Open()
 
        ' Create OleDbCommand object and select data from worksheet Sheet1
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn)
 
        ' Create new OleDbDataAdapter
        Dim oleda As OleDbDataAdapter = New OleDbDataAdapter()
 
        oleda.SelectCommand = cmd
 
        ' Create a DataSet which will hold the data extracted from the worksheet.
        Dim ds As DataSet = New DataSet()
 
        ' Fill the DataSet from the data extracted from the worksheet.
        oleda.Fill(ds, "Employees")
 
        ' Bind the data to the GridView
        DataGrid1.DataSource = ds.Tables(0).DefaultView
        DataGrid1.DataBind()
            
        ' Close connection
        oledbConn.Close()
 

Comments are closed.