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
Related
I am trying to read Excel, the code I am using runs in one project and is giving error "External table is not in the expected format." for same Excel Input in another project. What may be the issue for code to fail?- My connection string is " strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";"
You need to put single quotes around the Extended properties value.
from here
1. conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.15.0;Data Source=C:\Users\Input.xlsx;Extended Properties='Excel 15.0 Xml'");
2. conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.14.0;Data Source="+FilePath+";Extended Properties='Excel 14.0 Xml'");
3. conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Input.xlsx;Extended Properties='Excel 12.0 Xml'");
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()
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)
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';
I'm importing data from an Excel file in ASP.NET using OleDB. After finishing the import, I want to delete the file using the command System.IO.File.Delete(), but it throws the following exception:
The process cannot access the file '...29.xls' because it is being used by another process.
I used the following code to open and close the file:
Dim fajl As String
fajl = MapPath("fajlovi/" + Request.QueryString("ID"))
Dim sConnectionStringExcel As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fajl & ";Extended Properties=Excel 8.0;"
Dim objConnExcel As New OleDbConnection(sConnectionStringExcel)
objConnExcel.Open()
Dim objCmdSelectExcel As New OleDbCommand("SELECT ZavedenKodPov, Ime, Mjesto, Adresa, JMBG, LicniBroj, ZaposlenKod, Nepoznat, Umro, Penzioner, Reon, VoziloProizvodjac, VoziloModel, VoziloRegistracija, Nekretnina, Datum, KontoBroj, NazivKonta, OpisPromjene, Dug, Pot FROM [Sheet1$]", objConnExcel)
Dim objAdapterExcel As New OleDbDataAdapter()
objAdapterExcel.SelectCommand = objCmdSelectExcel
Dim objDatasetExcel As New DataSet()
objAdapterExcel.Fill(objDatasetExcel, "XLData")
Dim tExcel As DataTable
tExcel = objDatasetExcel.Tables(0)
'.
'.
'.
objConnExcel.Close()
System.IO.File.Delete(fajl)
Any ideas what I'm doing wrong?
dispose of the command and connection, preferably wrapped in a using statement. then you should be able to delete the file.