VB.NET reading xlsx file gives not a valid path - vb.net

I can't seem to read a .xlsx file using the following connection string:
Webconfig
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
Code File
conStr = ConfigurationManager.ConnectionStrings("Excel07ConString").ConnectionString
Dim connExcel As New OleDbConnection(conStr)
connExcel.Open()
I have been getting this error:
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "'F:\Ishan\Projects\ImportExcel2DB\ImportExcel2DB\Files\Whole Extract.xlsx' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.".
and yes there is file at this specific location. Any help would be appreciated!

The HDR needs to be either Yes or No. See my project below
Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim reader As New CSVReader()
Dim ds As DataSet = reader.ReadCSVFile("filename", True)
End Sub
End Module
Public Class CSVReader
Public Function ReadCSVFile(ByVal fullPath As String, ByVal headerRow As Boolean) As DataSet
Dim path As String = fullPath.Substring(0, fullPath.LastIndexOf("\") + 1)
Dim filename As String = fullPath.Substring(fullPath.LastIndexOf("\") + 1)
Dim ds As DataSet = New DataSet()
Dim header As String
If headerRow Then
header = "Yes"
Else
header = "No"
End If
Try
If File.Exists(fullPath) Then
Dim ConStr As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=""Text;HDR={1};FMT=Delimited\""", path, header)
Dim SQL As String = String.Format("SELECT * FROM {0}", filename)
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(SQL, ConStr)
adapter.Fill(ds, "TextFile")
ds.Tables(0).TableName = "Table1"
End If
For Each col As DataColumn In ds.Tables("Table1").Columns
col.ColumnName = col.ColumnName.Replace(" ", "_")
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return ds
End Function
End Class

Related

vb.net import csv file to devexpress gridview

Currently Im facing problem in importing csv file to devexpress gridview,When i execute the code, the following error showed 'C:\New folder\QtimeAutomotiveByLot_new.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides. and the filepath works perfectly fine on my side. my code is as follow, can anyone guide me on this?
asp.net
<dx:ASPxGridView ID="DetailGridx" runat="server" OnDataBinding="DetailGridx_DataBinding">
vb.net
Protected Sub DetailGridx_DataBinding(sender As Object, e As EventArgs)
Dim dt1 As New DataTable()
Dim csvFileFolder As String = "C:\New folder\QtimeAutomotiveByLot_New.csv"
'Dim csvFile As String = "QtimeAutomotiveByLot_New.csv"
Dim strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + csvFileFolder + ";Extended Properties='Text;HDR=YES;IMEX=1;';"
Dim connx As New OleDbConnection(strCon)
Dim adapter1 As New OleDbDataAdapter
connx.Open()
Dim sql As New OleDbCommand("Select * FROM [" + csvFileFolder + "]", connx)
adapter1.SelectCommand = sql
adapter1.Fill(dt1)
connx.Close()
Dim detailGrid As ASPxGridView = CType(sender, ASPxGridView)
Dim RowLotID As String = TryCast(sender, ASPxGridView).GetMasterRowFieldValues("LOTID")
Dim ddata As DataView = New DataView(dt1)
ddata.RowFilter = "LOTID = '" + RowLotID + "'"
detailGrid.DataSource = ddata
detailGrid.DataBind()
End Sub
Sounds like your current connection string to read CSV file is wrong. Unlike reading Excel files, when reading CSV files we're not specifying actual file name, but directory path where it belongs (see this issue).
The following example shows how to read CSV file using Jet 4.0 provider. Note that instead of setting IMEX=1, use FMT=Delimited property because IMEX primarily used for XLS and XLSX file format:
Protected Sub DetailGridx_DataBinding(sender As Object, e As EventArgs)
Dim dt1 As New DataTable()
Dim csvFileFolder As String = "C:\New folder\"
Dim csvFile As String = "QtimeAutomotiveByLot_New.csv"
' specify directory path containing CSV file as data source
Dim strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + csvFileFolder + ";Extended Properties='Text;HDR=YES;FMT=Delimited';"
Dim connx As New OleDbConnection(strCon)
Dim adapter1 As New OleDbDataAdapter
connx.Open()
' specify actual file name here
Dim sql As New OleDbCommand("Select * FROM [" + csvFile + "]", connx)
adapter1.SelectCommand = sql
adapter1.Fill(dt1)
connx.Close()
Dim detailGrid As ASPxGridView = CType(sender, ASPxGridView)
Dim RowLotID As String = TryCast(sender, ASPxGridView).GetMasterRowFieldValues("LOTID")
Dim ddata As DataView = New DataView(dt1)
ddata.RowFilter = "LOTID = '" + RowLotID + "'"
detailGrid.DataSource = ddata
detailGrid.DataBind()
End Sub

How to validate emails from a datagridview (VBA) before i put it in SQL Server

I want to import a .xlsx file into a datagridview and then save it in SQL Server. But before I save it, I want to check if all emails are valid or not, and just save the records with valid emails.
Like, it needs to be at least: (1 character)#(3 characters).(2 characters)
but still, it can be like this:
a#abc.def.ghi.com
with a domain and sub-domains
This is my code so far, can someone please help me?
Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class Importar
Dim conn As OleDbConnection
Dim dtr As OleDbDataReader
Dim dta As OleDbDataAdapter
Dim dts As DataSet
Dim excel As String
Dim counter As Integer
Dim totalR As Integer
'------------------------------------------------------------------BOTÃO PARA IMPORTAR DADOS EXCEL PARA DATAGRIDVIEW----------------------------------------------------------------------'
Private Sub btnImportar_Click(sender As Object, e As EventArgs) Handles btnImportar.Click
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments '"C:\Users\Utilizador\Documents"
OpenFileDialog1.Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"
If (OpenFileDialog1.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
Dim fi As New FileInfo(OpenFileDialog1.FileName)
Dim FileName As String = OpenFileDialog1.FileName
excel = fi.FullName
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties=Excel 12.0;") 'provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;")
dta = New OleDbDataAdapter("Select * From [Folha1$]", conn)
dts = New DataSet
dta.Fill(dts, "[Folha1$]")
dtgFicheiro.DataSource = dts
dtgFicheiro.DataMember = "[Folha1$]"
End If
conn.Close()
dtgFicheiro.Columns(0).Name = "ID"
dtgFicheiro.Columns(1).Name = "Nome"
dtgFicheiro.Columns(2).Name = "Email"
totalR = dtgFicheiro.Rows.Count
MessageBox.Show("O ficheiro tem um total de " & totalR & "linhas.")
btnValidar.Enabled = True
btnImportar.Enabled = False
End Sub
'-----------------------------------------------------------------------EXPORTAR DADOS PARA SQL SERVER-------------------------------------------------------------------'
Private Sub btnGuardar_Click(sender As Object, e As EventArgs) Handles btnGuardar.Click
For Each Row As DataGridViewRow In dtgFicheiro.Rows
Dim constring As String = "Data Source=DESKTOP-NMOL9GQ\SQLEXPRESS;Initial Catalog=EMAILS;INTEGRATED SECURITY=SSPI"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand(" INSERT INTO MAILS VALUES (#ID, #Nome, #Emails)", con)
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#ID", Row.Cells("ID").Value)
cmd.Parameters.AddWithValue("#Nome", Row.Cells("Nome").Value)
cmd.Parameters.AddWithValue("#Emails", Row.Cells("Email").Value)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Next
MessageBox.Show("Registos guardados.")
End Sub
Private Sub btnSair_Click(sender As Object, e As EventArgs) Handles btnSair.Click
Close()
End Sub
End Class
You can use Regular Expressions to check if the Email is valid(Requires a Reference to "Microsoft VBScript Regular Expressions 5.5"):
Public Function TestEmail(Email As String)
Dim EmailRegEx As String
EmailRegEx = "^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$"
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = EmailRegEx
End With
If regEx.Test(Email) Then
'Email valid
Debug.Print "valid"
Else
'Email not valid
Debug.Print "invalid"
End If
End Function
Modify this Function to return true or false and you can implement it into your code
(Regular Expression taken from http://emailregex.com/)
Can't quite read your code very well for some reason.
I suggest using regular expressions - they are fast and commonly used for the task. This site is fantastic as a reference - http://www.regular-expressions.info/email.html
Actually the discussion on there is very thorough and it's pointless me rehashing it.

Type 'UploaderEventArgs' is not defined

I tried the below code to upload a file to sql server table using vb.net command button. But while clicking build getting error in UploaderEventArgs.
Type 'UploaderEventArgs' is not defined.
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Protected Sub UploadAttachments1_FileUploaded(ByVal sender As Object, ByVal args As UploaderEventArgs)
'set connection string
Dim connectionString As String = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
' Read the file and convert it to Byte Array
Dim data() As Byte = New Byte((args.FileSize) - 1) {}
'get file extension
Dim extensioin As String = args.FileName.Substring((args.FileName.LastIndexOf(".") + 1))
Dim fileType As String = ""
'set the file type based on File Extension
Select Case (extensioin)
Case "doc"
fileType = "application/vnd.ms-word"
Case "docx"
fileType = "application/vnd.ms-word"
Case "xls"
fileType = "application/vnd.ms-excel"
Case "xlsx"
fileType = "application/vnd.ms-excel"
Case "jpg"
fileType = "image/jpg"
Case "png"
fileType = "image/png"
Case "gif"
fileType = "image/gif"
Case "pdf"
fileType = "application/pdf"
End Select
Dim stream As Stream = args.OpenStream
'read the file as stream
stream.Read(data, 0, data.Length)
Dim con As SqlConnection = New SqlConnection(connectionString)
Dim com As SqlCommand = New SqlCommand
com.Connection = con
'set parameters
Dim p1 As SqlParameter = New SqlParameter("#Name", SqlDbType.VarChar)
Dim p2 As SqlParameter = New SqlParameter("#FileType", SqlDbType.VarChar)
Dim p3 As SqlParameter = New SqlParameter("#Data", SqlDbType.VarBinary)
p1.Value = args.FileName
p2.Value = fileType
p3.Value = data
com.Parameters.Add(p1)
com.Parameters.Add(p2)
com.Parameters.Add(p3)
com.CommandText = "Insert into Files (Name,FileType,Data) VALUES (#Name,#FileType,#Data)"
con.Open()
'insert the file into database
com.ExecuteNonQuery()
con.Close()
End Sub
End Class
Source Link to the above code:
http://ajaxuploader.com/h/Save-Files-to-Database-using-FileUpload-Control.htm
It looks like UploaderEventArgs is part of the framework the company you linked offers, so you need to download and install it first. It's not part of the regular .NET libraries.

what is the correct format for calling a db in access, with a 'folder with spaces'?

Public connstring As String = "Provider = Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\blablabla\Document\Visual Studio 2013\Project\rentalsystem\rental_db.accdb"
i placed this line of code under a module so i wont have to call it everytime. and this is the code that the code above is connected to...
Public Sub loadLVusers()
LVusers.Items.Clear()
Dim sqlcode As String = "select id_code, user_lastname, user_firstname, user_midname, user_username, user_password, user_email, user_privilege from tblUsers"
Dim sqlcomd As New OleDb.OleDbCommand(sqlcode)
sqlcomd.Connection = New OleDb.OleDbConnection(connstring)
sqlcomd.Connection.Open()
Dim DA As New OleDb.OleDbDataAdapter(sqlcomd)
Dim DS As New DataSet
DA.Fill(DS, "Pi")
If DS.Tables("Pi").Rows.Count > 0 Then
Dim Ic(100) As String
For r = 0 To DS.Tables("Pi").Rows.Count - 1
For c = 0 To DS.Tables("Pi").Columns.Count - 1
Ic(c) = DS.Tables("Pi").Rows(r)(c).ToString
Next
Dim LVI As New ListViewItem(Ic)
LVusers.Items.Add(LVI)
Next
End If
End Sub
now when the form/window that it is attached to loads, the form/window does not open. and then it highlights
sqlcomd.Connection = New OleDb.OleDbConnection(connstring)
so im guessing that has something to do with the file path format

Problems reading an Excel file in VB.net

I have been trying to upload and read an Excel file (.xls, or .xlsx)
I am upploading sucessfully using this code:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim filepath As String = ""
If FileUpload1.HasFile Then
Try
Dim filename As String = FileUpload1.PostedFile.FileName
Dim extension = (filename.Substring(filename.LastIndexOf("."), (filename.Length() - filename.LastIndexOf("."))))
If extension = ".xlsx" Or extension = ".xls" Then
filepath = "\" & Common.toUnix(Now) & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
' ==== NOW READ THE FILE
Else
StatusLabel.InnerText = "Only Excel file types are accepted (.xls/.xlsx)<br> File Uploaded had extension: " & extension
End If
Catch ex As Exception
StatusLabel.InnerText = "Upload status: The file could not be uploaded. The following error occured: " + ex.ToString()
End Try
End If
End Sub
It uploads OK, but when trying to read the file I get this error:
System.Data.OleDb.OleDbException (0x80004005): The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data.
I am using code to read similar to this:
vb.net traversing an xls / xlsx file?
Therefore the connection is as follows:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0" & _
";Data Source=" & ExcelFile & _
";Extended Properties=Excel 8.0;"
Dim conn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Dim excelDataSet As New DataSet()
Try
conn = New OleDbConnection(connString)
conn.Open() '<<< ERROR IS RAISED ON THIS LINE
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets(dt.Rows.Count) As String
Dim i As Integer = 0
For Each row As DataRow In dt.Rows
excelSheets(i) = row("payments").ToString
System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
If i = SheetNumber Then
Exit For
End If
Next
..................
I'm uploading to a shared server so don't have control as to permissions as such, but I do have read/write permissions and uploading Images works OK, but it's reading this file that I can't get to work.
NOTE
This error occurs with .xls files, when using .xlsx I get this error:
System.Data.OleDb.OleDbException (0x80004005): Cannot update. Database or object is read-only. at System.Data.OleDb.OleDbConnectionInternal
This error occurs on this line:
For Each row As DataRow In dt.Rows
So it appears it is uplpoading and opening the file OK, but not reading the rows....
I am not sure why that's happening either!
Any help would be much appreciated!
ACE is brutal, have troubles with it all the time and it cannot exist on a System in both 32 and 64 bit version at the same time. As a result I just dont use it at all.
To read an Excel XLSX file I use "EPPlus" which has proven to be very easy to deal with and extreamly efficient.
It ONLY works with XLSX (not XLS)
Example... (simple just pulls out first sheet as a datatable)
Public Function XlsxToDataTable(byteStream As IO.MemoryStream) As DataTable
Using pac As New OfficeOpenXml.ExcelPackage(byteStream)
Dim wb As OfficeOpenXml.ExcelWorkbook = pac.Workbook
Dim ws As OfficeOpenXml.ExcelWorksheet = wb.Worksheets(1) '1 based
Dim out As New DataTable
For iC As Integer = 1 To ws.Dimension.End.Column
out.Columns.Add(ws.Cells(1, iC).Value.ToString)
Next
For iR As Integer = 2 To ws.Dimension.End.Row
Dim nr As DataRow = out.NewRow
For iC As Integer = 1 To ws.Dimension.End.Column
nr(iC - 1) = ws.Cells(iR, iC).Value
Next
out.Rows.Add(nr)
Next
Return out
End Using
End Function