VB.net reading Excel page - asp.net

I am trying to read an Excel page but I get the following error:
Input string was not in a correct format.Couldn't store <555-555-5555> in PHONE_NUM Column. Expected type is Double.
It seems that the oledb command is expecting the column to be of type double (but, in fact, it is a string for phone numbers). I think I read somewhere that this happens because the command looks as the first couple of items in the column and determines what the type should be based off of that. Is there anyway to always read all values in as a string?
This is the code I am using:
Dim connection As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim adapter As New OleDb.OleDbDataAdapter
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + myFile + ";Extended Properties=Excel 12.0;"
Dim pgOne As String = "Page1$"
Dim pgTwo As String = "Page2$"
Dim selectOne As String = "SELECT * FROM [" & pgOne & "] WHERE COL1<>''"
Dim selectTwo As String = "SELECT * FROM [" & pgTwo & "]"
connection = New OleDb.OleDbConnection(connString)
Try
If connection.State = ConnectionState.Open Then
Else
connection.Open()
End If
command = New OleDb.OleDbCommand(selectOne, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Table1")
adapter.SelectCommand.CommandText = selectTwo
adapter.Fill(ds, "Table2")
Catch ex As OleDb.OleDbException
Finally
adapter.Dispose()
If (Not command Is Nothing) Then
command.Dispose()
End If
connection.Close()
End Try

You can get the tables to fill as strings in one of two ways. If you want to read them in as only a string you can add a part to your connection string that should read intermixed datatype columns as text. Alternatively force them into string types by reading in a header row as data. You can also use schemas to read in table definitions but I would need to find a little more info on that if these don't work for you.
The first option is simpler to do:
First change your connection string to add IMEX=1
'Add IMEX=1
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;IMEX=1;Data Source=" + myFile + ";Extended Properties=Excel 12.0;"
This should then provide you with String based columns on any datacolumns that have mixed data types in their rows.
Another way to do it is force the string column type by reading the header row as a datarow by specifying there is no header row in your connection string. You can then remove this after to have a string column of data.
'Add HDR=NO
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;HDR=NO;Data Source=" + myFile + ";Extended Properties=Excel 12.0;"
I will research a little more if these don't work for you.

As mentioned, I was unable to fix this so I just ended up creating a schema manually and formatting the data as it was bound.

Related

Using parameterized query is causing data type mismatch. Any ideas?

I have a dropdownList with control ID of HourlyCharter.
Then on codebehind, I am trying to query records from the database where hourly is equal to the value of HourlyCharter.
If I use this code:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = " & HourlyCharter.SelectedValue
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
It works.
If I use parameterized query such as this:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = #hourly"
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
'We use parametized query to prevent sql injection attack
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
I get following error:
Data type mismatch in criteria expression
Hourly is of Number data type and we are using Access 2010 database.
Any ideas how to resolve this?
'open recordset to receive db values
rs = cmd.ExecuteReader()
' This acts like the (Not RecordSource.Eof) in ASP 3.0 to loop and retrieve records.
While rs.Read()
' If rs("city") <> "" Then
Dim tipValue As Decimal = rs("tip")
Dim totValue = rs("total")
' Else
' End If
Dim tp As String = [String].Format("{0:C}", tipValue)
Dim tot As String = [String].Format("{0:C}", totValue)
lblTip.Text = tp
lblTotal.Text = tot
End While
You need to make sure the object you put in the parameter is also a numeric type. SelectedValue is a string.
Dim p1 As New OleDbParameter("#hourly", Decimal.Parse(HourlyCharter.SelectedValue))
That's where the data type mismatch happens - it's expecting a number but it's getting a string.
Instead of
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
You can try
cmd.Parameters.AddWithValue("#hourly", HourlyCharter.SelectedValue)
Try specifying the datat type of the parameter. You can do it after creating it:
p1.OleDbType = OleDb.OleDbType.Numeric
You can also do it on the constructor, but it requires a lot more parameters and I'm not sure you have all those nor I do know what they do.

The Microsoft Jet database engine could not find the object 'Sheet1$'

I'm attempting to read a spreadsheet file called Book1.xls which contains a worksheet called Sheet1
However I'm getting the following 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.
Here is a snippet of the code I'm using:
Dim dt As DataTable = New DataTable()
Select Case fileExt
Case ".csv"
Dim reader As New CsvReader
dt = reader.GetDataTable(filePath)
Case ".xls", ".xlsx"
Dim oleDbConnStr As String
Select Case fileExt
Case ".xls"
oleDbConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
Case ".xlsx"
oleDbConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
End Select
Using oleDbConn As OleDbConnection = New OleDbConnection(oleDbConnStr)
oleDbConn.Open()
Dim oleDbCmd As New OleDbCommand("SELECT * FROM [Sheet1$]", oleDbConn)
Dim oleDbDa As New OleDbDataAdapter(oleDbCmd)
oleDbDa.Fill(dt)
oleDbConn.Close()
End Using
End Select
I can't understand why the code cannot find my worksheet. Why is this, and how can I resolve it?
I've found the problem.
It seems the spreadsheet was being saved to the wrong location, so filepath wasn't pointed to a file which exists.
I didn't check this at first because I assumed a different error message would appear. Something like "Book1.xls could not be found". However it seems like if it doesn't exist, then the message will just state that it cannot find the Worksheet.
If file name has additional dot character like below:
sample.data.csv
next select statement:
SELECT * FROM [sample.data.csv]
with connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Data\"; Extended Properties="text;HDR=Yes;Format=Delimited;";
will fail with exception:
Additional information: The Microsoft Jet database engine could not find the object 'sample.data.csv'. Make sure the object exists and that you spell its name and the path name correctly.
Also - make sure you don't have the file open in Excel already. You won't be able to read the file if it's open somewhere else. I had the same error and realized I had the file open in Excel.
Not sure, I have some similar code (C#) that works well...
Maybe you can spot a difference?
string connectionString = string.Format(Thread.CurrentThread.CurrentCulture, "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;'", excelFilePath);
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = #"SELECT [File], [ItemName], [ItemDescription], [Photographer name], [Date], [Environment site] FROM [Metadata$]";
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
.......
}
}
}
connection.Close();
}
}
Try renaming your sheet; or explicitly adding columns; or checking if it's case sensitive.
Change your Excel file location, this error will be resolved.
may put your file in the same folder where your source present
best solution through vb coded from this link, all credits to these folks-
http://www.vbforums.com/showthread.php?507099-data-from-excel-sheet-to-datagrid-(vb)
C# My expected solution below
string connString = "Driver={Microsoft Excel Driver (*.xls)};READONLY=FALSE;DriverId=790;Dbq=" + "C:\\Users\\BHARAVI\\Documents\\visual studio 2013\\Projects\\ERP\\ERPAutomation\\Assets\\Data\\Data.xls";
OdbcConnection conn = new OdbcConnection(connString);
conn.ConnectionTimeout = 500;
OdbcCommand CMD = new OdbcCommand("SELECT * FROM [Sheet1$]", conn);
OdbcDataAdapter myDataAdaptor = new OdbcDataAdapter(CMD);
DataSet ds = new DataSet();
myDataAdaptor.Fill(ds ,"Sheet1");
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
loginId = dr["LoginId"].ToString();
encryptedPassword = dr["PWD"].ToString();
URL = dr["URL"].ToString();
}

Cannot delete excel file after importing data from it using OleDB, says it is being used by another process

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.

Inserting multiple dropdownlist values in a field in database (ASP)

I have three dropdownlist which values are to be inserted in one particular field in the database. But i am new to ASP.
This are my following codes:
Dim strConn = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim myConn As New SqlConnection(strConn)
Dim cmd = "INSERT INTO [IndividualWorkout] (WorkoutProgramName, WorkoutProgramPosted, WorkoutProgramDesc, IndividualWorkoutName, IndividualWorkoutTips, TimingID) VALUES (#WorkoutProgramName, #WorkoutProgramPosted, #WorkoutProgramDesc, #IndividualWorkoutName, #IndividualWorkoutTips, #TimingID)"
Dim myCmd As New SqlCommand(cmd, myConn)
myCmd.Parameters.AddWithValue("#WorkoutProgramName", TextBox1.Text)
myCmd.Parameters.AddWithValue("#WorkoutProgramPosted", TextBox2.Text)
myCmd.Parameters.AddWithValue("#WorkoutProgramDesc", TextBox3.Text)
myCmd.Parameters.AddWithValue("#IndividualWorkoutName", TextBox4.Text)
myCmd.Parameters.AddWithValue("#IndividualWorkoutTips", TextBox5.Text)
myCmd.Parameters.AddWithValue("#TimingID", DropDownList4.SelectedValue.ToString())
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myConn.Close()
Could anyone guide me/help me with the editing of the following code so that the 3 dropdownlist values which were selected will go in the TimingID.
Thanks
If you want to concatenate the values, you can do it like this.
string s = DropDownList4.SelectedValue.ToString() + "|"
+ DropDownList5.SelectedValue.ToString() + "|"
+ DropDownList6.SelectedValue.ToString();
myCmd.Parameters.AddWithValue("#TimingID", s);
Then you will have to parse out the 3 values when you retrieve the data from that field with a .Split() or similar function.
Just as a note, it seems odd to have an ID field use concatenated strings. I'm assuming this field requires uniqueness, which seems at risk by using a combination of dropdown values. Do you have that covered?

Getting row Count only returns value of 1

I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.
Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
Dim sqlda2 As New SqlDataAdapter(comm2)
Dim dt2 As New DataTable
sqlda2.Fill(dt2)
Dim recordcount As Integer = dt2.Rows.Count
messagecountlbl.Text = recordcount
this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.
I have also tried the Select Count statement and it does the same thing.
Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
Aren't you missing quotes around Unread?
Also... you're susceptible to SQL Injection. Use Parameters instead
Also... if all you are doing is getting the number of rows, your code is overkill
I just noticed.... you Dimmed comm2 but your adapter uses comm
Your updated question was the route that I would have gone. This was why i said your initial code was overkill (in terms of memory usage...). DataAdapters and DataTables for one value is in no way efficient.
You might want to change your updated code to the following...
Again, look up SQL Injection to see why you should never (or at least try not to) build a sql string like that
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = #param"
sql.Parameters.AddWithValue("#param", Session("sessionvariable"))
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
It looks like you're missing a single quote at the beginning of the word "Unread".
...& "' AND columnname = 'Unread'")
I note that your first line declares a variable called comm2 but you don't use it later - instead you're using simply comm.
With that in mind, the fact that you've omitted the quotes around Unread will still be relevant.
Fix I have added this to the post since there is a 24 hr wait to answer question: I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult

Resources