Monday, June 27, 2005

Importing Excel data to Access Database in ASP.NET

The code below gives the solution for importing excel data to access database. I needed this when doing a tool on skill search of employees.


TO DOWNLAOD THE EXCEL SHEET TO PARTICULAR PATH

Dim savePath As String = "C:\Inetpub\wwwroot\naviwebpage\Database\"
Dim postedFile = UploadFile.PostedFile
Dim filename As String = Path.GetFileName(postedFile.FileName)
txtExportFilename.Text = filename 'ASSIGNING THE FILENAME TO A TEXTBOX
If Not (UploadFile.PostedFile Is Nothing) Then
Try
'Dim postedFile = UploadFile.PostedFile
' Dim filename As String = Path.GetFileName(postedFile.FileName)
Dim contentType As String = postedFile.ContentType
Dim contentLength As Integer = postedFile.ContentLength

postedFile.SaveAs(savePath & filename)
Label2.Text = postedFile.Filename & " uploaded" & _
"
content type: " & contentType & _
"
content length: " & contentLength.ToString()
Catch exc As Exception
Label2.Text = "Failed uploading file"
End Try
End If

IMPORTING DATA FROM EXCEL
Dim filenameEx, path As String
filenameEx = txtExportFilename.Text 'ASSIGINING THE FILENAME TO THE VARIABLE FROM THE TEXTBOX
path = "C:\Inetpub\wwwroot\naviwebpage\Database\" & filenameEx


'to convert excel it intO access
Dim AccessConn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Inetpub\wwwroot\naviwebpage\Database\naviwebpage.mdb")
Try
AccessConn.Open()

'FOR EXISTING TABLE
' Dim AccessCommand As New System.Data.OleDb.OleDbCommand("INSERT INTO [Export](F1,F2) SELECT * from [Excel 8.0;DATABASE=" & path & ";HDR=No;IMEX=1].[Sheet1$];", AccessConn)

'Working existing table for default path
'Dim AccessCommand As New System.Data.OleDb.OleDbCommand("INSERT INTO [Export](F1,F2) SELECT * from [Excel 8.0;DATABASE=C:\Inetpub\wwwroot\naviwebpage\Database\Wordlist.xls;HDR=No;IMEX=1].[Sheet1$];", AccessConn)


'FOR NEW TABLE CREATED EACH TIME
Dim AccessCommand As New System.Data.OleDb.OleDbCommand("SELECT * INTO [ALCON] FROM [Excel 8.0;DATABASE=" & path & ";HDR=yes;IMEX=1].[Sheet1$];", AccessConn)

AccessCommand.ExecuteNonQuery()
AccessConn.Close()
Catch ex As Exception
Label2.Text = ex.Message
Finally
AccessConn.Close()
'Label2.Text = "Export Success"
End Try


Hope this is helpful to who ever in need of this. Comments Please. Enjoy

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home