Save ASP classic form into a specific column in excel - asp-classic

I'd to know if it's possible to have my asp classic form saved into a excel file in a column after submit?
Thank you all.

use the Microsoft.Jet.OLEDB Driver to access the excel sheet like so:
dim conn : set conn = server.createObject("ADODB.Connection")
dim rs : set rs = server.createObject("adodb.recordset")
dim sql
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &_
"myExcelFile.xls;" &_
"Extended Properties=""Excel 8.0;HDR=YES;"""
then you yould use just sql to insert your data...
the possible connectionstrings for excel are listed here

THE BELOW CODE IS TO INSERT INTO AN EXISTING EXCEL FILE. THIS IS WHAT YOU NEED.
<%
Option Explicit
' OPEN DATABASE
dim objConn,strConnection,objRS,strQuery
'Set objConn = New ADODB.Connection
set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("TEST.xls") & "; Extended Properties=Excel 8.0;"
objConn.Open strConnection
'Set objRS = New ADODB.Recordset
set objRS = Server.CreateObject("ADODB.Recordset")
set objRS.ActiveConnection = objConn
' This is to Select A1:A1 and open the recordset
strQuery = "SELECT * FROM A1:A1"
objRS.Open strQuery
' This is to insert into A1:A1 a value that says: testttest
strQuery = "insert into [A1:A1] values('testttest')"
' Close and destroy the Connection object.
objConn.Execute strQuery
objConn.Close
Set objRS=Nothing
Set objConn=Nothing
%>
TO UPDATE A SPECIFIC COLUMN
You can do this: See here: http://bytes.com/topic/asp-classic/answers/620074-update-existing-excel-file-using-asp-urgent
and also here: Update Excel Sheet (in Classic ASP/Vbscript)

Related

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

insert data into ms access, using asp

im trying to insert a new row with new data to an ms access table, using asp page.
i have no background in asp, im an android developer, but those are my client specifications.
i know im doing something very wrong, but i dont know what...
can you please help me?
this is what i was trying to do:
<%
'define variables
dim conn, strsql, strMDBPath
Set conn = Server.CreateObject("ADODB.Connection")
'Connect to the database
strMDBpath = Server.MapPath("data.mdb")
conn.open "PROVIDER=MICROSOFT.JET.OLEDB.4.0;DATA SOURCE=" & strMDBPath
'On Error Resume Next
'write to the database
strSql = "INSERT INTO avi (id,first,last) VALUES ("4", '" yom "','" cobi "')"
conn.Execute(strSql)
'close database
conn.close
Set conn = nothing
%>
You're missing some ampersands.
strSql = "INSERT INTO avi (id,first,last) VALUES (4, '" & yom & "', '" & cobi & "')"

Importing Excel to SQL Database using vb.net and 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()

Update Excel Sheet (in Classic ASP/Vbscript)

I tried to search for a code that would update a Excel (XLS) file in Classic-ASP but I cannot get it to work.
here is what I have:
<!--#include file="../adovbs.inc"-->
<%
' Open and Update and then Close The XLS File
Dim objConn
set objConn = Server.CreateObject("ADODB.Connection")
Dim FLConnect
Dim strSQLexcel
' Create the connection string.
FLConnect = "Provider=Microsoft.Jet.OLEDB.4.0 Data Source=" & Server.MapPath("TEST.xls") & "Extended Properties='Excel 8.0;HDR=No'"
' Create the SQL statement.
strSQLexcel= "UPDATE [Sheet1$A1:A1] SET F1='TestValue1'"
set objConn = Server.CreateObject("ADODB.Recordset")
'Set objConn = New ADODB.Connection
' Create and open the Connection object.
objConn.Open FLConnect
' Execute the insert statement.
objConn.Execute strSQLexcel
' Close and destroy the Connection object.
objConn.Close
%>
But I keep getting an error saying: " The connection cannot be used to perform this operation. It is either closed or invalid in this context. "
Thank you so much...
Your connection string is not right.
You have:
Provider=Microsoft.Jet.OLEDB.4.0 Data Source="
& Server.MapPath("TEST.xls") & "Extended Properties='Excel 8.0;HDR=No'"
You are missing a semi-colon after 4.0 and before Extended
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
& Server.MapPath("TEST.xls") & ";Extended Properties='Excel 8.0;HDR=No'"
See http://connectionstrings.com
This connection string worked best for me:-
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myExcel.xlsm;Extended Properties='Excel 12.0 Macro;HDR=YES';

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