Importing Excel to SQL Database using vb.net and asp.net - asp.net

Im currently building a project that lets users import Excel files via a web interface (built), which saves the file to the server (built), and then imports the data into the SQL Database on the server depending on a few of the user options (not built).
Im not familiar with SQL database tools within VS at all so I have been fumbling around for the better part of two days just trying to get everything set up. Im pretty sure I need to use BulkCopy, but Im not quite sure how to use it and I can't seem to find specific examples that explain it pertaining to my specific application.
So in my App_Data folder I have an .mdf title "Device Database." In that database I have three tables: "Galaxy Nexus", "Hercules" , and "Ruby"
I am trying to import four cells from each imported excel sheet to their respective tables.
I would like to import cell(2,2) to column1 in the table, cell(2,3) to column2, cell(3,2) to column3 and cell(1,1) to column4.
The code I am trying to accomplish this with is:
Dim ExcelContentType As String = "application/vnd.ms-excel"
Dim Excel2010ContentType As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim excelConnectionString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", SavedFile)
Using connection As New OleDbConnection(excelConnectionString)
Dim Command As OleDbCommand = New OleDbCommand("Select * FROM [Sheet1$]", connection)
connection.Open()
Using reader As DbDataReader = Command.ExecuteReader()
Dim sqlConnectionString As String = "Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True"
Using bulkCopy As New SqlBulkCopy(sqlConnectionString)
bulkCopy.DestinationTableName = DropDown1.SelectedItem.ToString
bulkCopy.WriteToServer(reader)
End Using
End Using
End Using
Where I am having trouble is, I do not know how to select certain cells from the excel sheet to import and I do not know how to copy those cells to specific columns in the specified table.
Any and all help is always appreciated.
Thanks,
Zach

Im posting an answer so that if anyone else stumbles upon this, they might be helped as well.
This is what got everything to work for me. (Shout out to kevin)
Protected Sub Button1_Click(sender As Object, e As System.EventArgs)
Dim appPath As String = Request.PhysicalApplicationPath
Dim con As New System.Data.SqlClient.SqlConnection
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
con.Open()
MsgBox("open")
con.Close()
MsgBox("close")
End Sub
This got the connection open after much trying and frustration.
This got the excel values imported to the database:
Using con As New SqlClient.SqlConnection With
{
.ConnectionString =
"Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
}
Using cmd As New SqlClient.SqlCommand With
{
.Connection = con,
.CommandText = "INSERT INTO " & """" & DropDownList1.SelectedItem.ToString & """" & "ColumnName1, ColumnName2)VALUES (#Col1,#Col2)"
}
cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "#Col1"})
cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "#Col2"})
cmd.Parameters(0).Value = "Value obtained from Excel"
cmd.Parameters(1).Value = "Value obtained from Excel"
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery
If Result <> 1 Then
MessageBox.Show("Insert failed.")
Else
MessageBox.Show("Row inserted.")
End If
End Using
End Using
Enjoy guys!

Use Excel Data Reader dll for this. It will read the excel file and give the Dataset as result.

simple code for 'abcConnectionString' as a connection string
and 'pqr_table' as sql table.
'Sheet1' is for the sheet1 of excel file.
important thing is the table format ie rows n columns of excel n database file should b same
her is the vb.net code foe veb application
one FileUpload with name 'FileUpload1'
and one button.
this code is in side the buton method
Dim excelConnectionString As String = String.Empty
Dim uploadPath As String = "~/Uploads/"
Dim filePath As String = Server.MapPath(uploadPath + FileUpload1.PostedFile.FileName)
Dim fileExt As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim strConnection As [String] = ConfigurationManager.ConnectionStrings("abcConnectionString").ConnectionString
If fileExt = ".xls" OrElse fileExt = "XLS" Then
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & filePath & "'" & "; Extended Properties ='Excel 8.0;HDR=Yes'"
ElseIf fileExt = ".xlsx" OrElse fileExt = "XLSX" Then
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=Excel 12.0;Persist Security Info=False"
End If
Dim excelConnection As New OleDbConnection(excelConnectionString)
Dim cmd As New OleDbCommand("Select * from [Sheet1$]", excelConnection)
excelConnection.Open()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader()
Dim sqlBulk As New SqlBulkCopy(strConnection)
sqlBulk.DestinationTableName = "pqr_table"
sqlBulk.WriteToServer(dReader)
MsgBox("Congratulations! Successfully Imported.")
excelConnection.Close()

simple code for 'abcConnectionString' as a connection string and 'pqr_table' as sql table. 'Sheet1' is for the sheet1 of excel file. important thing is the table format ie rows n columns of excel n database file should b same
here is the vb.net code foe veb application one FileUpload with name 'FileUpload1' and one button. this code is in side the buton method
Dim excelConnectionString As String = String.Empty
Dim uploadPath As String = "~/Uploads/"
Dim filePath As String = Server.MapPath(uploadPath + FileUpload1.PostedFile.FileName)
Dim fileExt As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim strConnection As [String] = ConfigurationManager.ConnectionStrings("abcConnectionString").ConnectionString
If fileExt = ".xls" OrElse fileExt = "XLS" Then
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & filePath & "'" & "; Extended Properties ='Excel 8.0;HDR=Yes'"
ElseIf fileExt = ".xlsx" OrElse fileExt = "XLSX" Then
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=Excel 12.0;Persist Security Info=False"
End If
Dim excelConnection As New OleDbConnection(excelConnectionString)
Dim cmd As New OleDbCommand("Select * from [Sheet1$]", excelConnection)
excelConnection.Open()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader()
Dim sqlBulk As New SqlBulkCopy(strConnection)
sqlBulk.DestinationTableName = "pqr_table"
sqlBulk.WriteToServer(dReader)
MsgBox("Congratulations! Successfully Imported.")
excelConnection.Close()

Related

getting data from database asp.net

i am trying to get data from ms access database using this code but i can not this is my code is this correct
Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"
Using connection As New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand(query)
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(query, connection)
Dim com As New OleDbCommand(query, connection)
connection.Open()
'on the line below I get an error: connection property has not been initialized
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
Label1.Text = (reader(0).ToString())
End While
reader.Close()
End Using
Database
|data|
asl
trying to get data from database and trying to show it in a label is this possible
You never associated cmd with the connection, and you never use com or adapter. This is the sort of thing you can figure out by stepping through your code line by line and inspecting the state of it.
Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"
Using connection As New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand(query, connection)
connection.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
Label1.Text = (reader(0).ToString())
End While
reader.Close()
End Using
Also, your code is vulnerable to a SQL Injection Attack. You should not be concatenating strings together to form your queries. You should instead use parameterized queries.

Error in Export data from excel to sql server database

I have try to copy data from excel sheet to sql server using sql bulk copy, but
I got error whenever try to open connection of excel sheet database I mean Microsoft ace oledb connection.
I have try "Enable 32-Bit Application = true" in Application Pool then It works fine, but I don't want to set it true.
How I can fix it??
I have share sample code in this excel_con.Open() comes error this point
'Upload and save the file
Dim excelPath As String = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName)
FileUpload1.SaveAs(excelPath)
Dim connString As String = String.Empty
Dim extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Select Case extension
Case ".xls"
'Excel 97-03
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & excelPath & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1"""
Exit Select
Case ".xlsx"
'Excel 07 or higher
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & excelPath & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"""
Exit Select
End Select
Using excel_con As New OleDbConnection(connString)
excel_con.Open()
Dim sheet1 As String = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing).Rows(0)("TABLE_NAME").ToString()
Dim dtExcelData As New DataTable()
This is the error screen shot

Can't retrive image from mdb database this program show error "parameter in not valid"

Try
'connection string
Dim dbpath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
dbpath = New Uri(dbpath).LocalPath
Dim my_connection As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=D:\DataBase\KhandagramPS.mdb"
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
Dim DR As OleDbDataReader
'Dim source As String
'query string
Dim my_query As String = "SELECT sl_no,f_name,dob,sex,add,reg,[class],a_date,a_per,r_a_per,f_status,[name],photo,document FROM " & TextBox2.Text & " where sl_no=" & TextBox3.Text & " ;"
'create a connection
Dim my_dbConnection As New OleDbConnection(my_connection)
my_dbConnection.Open()
'create a command
Dim my_Command As New OleDbCommand(my_query, my_dbConnection)
DR = my_Command.ExecuteReader()
While (DR.Read())
txtslno.Text = (DR(0).ToString())
txtfname.Text = (DR(1).ToString())
Date1.Text = (DR(2).ToString())
comsex.Text = (DR(3).ToString())
txtadd.Text = (DR(4).ToString())
txtreg.Text = (DR(5).ToString())
comclass.Text = (DR(6).ToString())
Date2.Text = (DR(7).ToString())
txtaper.Text = (DR(8).ToString())
txtraper.Text = (DR(9).ToString())
txtfstatus.Text = (DR(10).ToString())
txtname.Text = (DR(11).ToString())
Dim ImageBuffer = CType(DR(12), Byte())
Dim imgStrm As New MemoryStream(ImageBuffer, True)
imgStrm.Write(ImageBuffer, 0, ImageBuffer.Length)
Dim img As Image = Image.FromStream(imgStrm)
PictureBox1.Image = img
End While
'close connection
my_dbConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
I suspect some error in your Byte-Array to Image conversion. Make sure that your Byte-Array is not messed up. Use this function instead.
Private Function getImage(imageBuffer as Byte())
Using ms as new IO.MemoryStream(imageBuffer)
Dim img = ImageIO.FromStream(ms)
Return img
End Using
End Function
my 2 cents: you shouldn't store images in an mdb file (unless things have changed a lot in the past few years). store images in a separate directory and store the file paths in the mdb so the image can be found when needed.

The Microsoft Jet database engine could not find the object 'Sheet1$' in vb.net

here am trying to keep excel sheet data in to data set.help me to over from this error
The Microsoft Jet database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.
Dim ds As System.Data.DataSet
Dim RecTab As Data.DataTable
Dim RecTab1 As Data.DataTable
Dim Rectab2 As Data.DataTable
Dim ds1 As System.Data.DataSet
Dim HFCell As String
Dim HTCell As String
Dim FilePath As String
HFCell = "A1"
HTCell = "B1"
m_FileName = "Data.xls"
FilePath = Server.MapPath("..\TankGauge\Data_Mgr") & "\" & m_FileName
Try
Dim connectionString As String = ""
Try
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0;"
MyConnection = New OleDbConnection(connectionString)
MyConnection.Open()
dataAdapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", MyConnection)
ds = New Data.DataSet
dataAdapter.Fill(ds)
RecTab = ds.Tables(0)
MyConnection.Close()
In your Excel workbook, is there a worksheet named Sheet1? If not, rename the sheet or change your code to call out the sheet you want to get data from.
I believe the database driver you're using won't work. Try changing:
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0;"
to:
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0;"

oRecordset in ASP.NET mySQL

I have this mySQL code that connects to my server. It connects just fine:
Dim MyConString As String = "DRIVER={MySQL ODBC 3.51 Driver};" & _
"SERVER=example.com;" & _
"DATABASE=xxx;" & _
"UID=xxx;" & _
"PASSWORD=xxx;" & _
"OPTION=3;"
Dim conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "select * from userinfo WHERE emailAddress = '" & theUN & "'""
MyCommand.ExecuteNonQuery()
conn.Close()
However, i have an old Classic ASP page that uses "oRecordset" to get the data from the mySQL server:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=example.com; PORT=3306; DATABASE=xxx; USER=xxx; PASSWORD=xxx; OPTION=3;"
sqltemp = "select * from userinfo WHERE emailAddress = '" & theUN & "'"
oRecordset.Open sqltemp, oConnection,3,3
And i can use oRecordset as follows:
if oRecordset.EOF then....
or
strValue = oRecordset("Table_Name").value
or
oRecordset("Table_Name").value = "New Value"
oRecordset.update
etc...
However, for the life of me, i can not find any .net code that is similar to that of my Classic ASP page!!!!!
Any help would be great! :o)
David
This is what you have to do:
instead of MyCommand.ExecuteNonQuery you should use MyCommand.ExecuteQuery and assign it to DataReader.
Check out this sample:
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()
'declaring the objects
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection. you need to provide password for sql server
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
HTH
Dim conn As OdbcConnection = New OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=xxx.com; DATABASE=xxx; UID=xxx; PASSWORD=xxx; OPTION=3;")
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "SELECT * FROM userinfo"
Dim rst = MyCommand.ExecuteReader()
While rst.Read()
response.write(rst("userID").ToString())
End While
conn.Close()
Dim email As String = "anyone#anywhere.com"
Dim stringValue As String
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql = "Select ... From userInfo Where emailAddress = #Email"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
While reader.Read()
stringValue = reader.GetString(0)
End While
End Using
conn.Close()
End Using
'To do an Update
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Update userInfo Set Column = #Value Where PK = #PK"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
cmd.ExecuteNonQuery()
End Using
End Using
'To do an Insert
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Insert userInfo(Col1,Col2,...) Values(#Value1,#Value2...)"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Col1", value1)
cmd.Parameters.AddWithValue("#Col2", value2)
...
cmd.ExecuteNonQuery()
End Using
End Using
First, even in ASP Classic, it is an absolutely horrid approach to concatenate a value directly into a SQL statement. This is how SQL Injection vulnerabilities happen. You should always sanitize values that get concatenated into SQL statements. In .NET, you can use parametrized queries where you replace the values that go into your query with a variable that begins with an # sign. You then add a parameter to the command object and set your value that way. The Command object will sanitize the value for you.
ADDITION
You mentioned in a comment that your ASP Classic code is shorter. In fact, the .NET code is shorter because there are a host of things happening that you do not see and have not implemented in your ASP Classic code. I already mentioned one which is sanitizing the inputs. Another is logging. Out of the box, if an exception is thrown, it will log it in the Event Log with a call stack. To even get a call stack in ASP Classic is a chore much less any sort of decent logging. You would need to set On Error Resume Next and check for err.number <> 0 after each line. In addition, without On Error Resume Next, if an error is thrown, you have no guarantee that the connection will be closed. It should be closed, but the only way to know for sure is to use On Error Resume Next and try to close it.
Generally, I encapsulate all of my data access code into a set of methods so that I can simply pass the SQL statement and the parameter values and ensure that it is called properly each time. (This holds true for ASP Classic too).

Resources