visual basic 2010, Importing excel files to my SQL using bulkcopy - vb.net

hello guys I'm having a problem with a project that I build
I'm trying to import excel files to sql server 2016 using bulkcopy and I got this error
"'DAFTAR1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long"
I think there is a problem with this code
Dim query_excel As String = "SELECT * from [" & file & "$]"
i tried all of this code on another pc and it works perfectly but on my pc it's getting that error, I don't know what did I wrong, I'm using visual basic 2010 professional edition, sql management server 2016 and microsoft office 2016
can anyone help me to figure what is wrong with the code ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
file = System.IO.Path.GetFileNameWithoutExtension(TextBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim koneksi_excel As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;Data Source='" & TextBox1.Text & "';Extended Properties=""Excel 12.0 Xml;HDR=YES;""")
koneksi_excel.Open()
Dim query_excel As String = "SELECT * from [" & file & "$]"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(query_excel, koneksi_excel)
Dim rd As OleDb.OleDbDataReader
rd = cmd.ExecuteReader()
Dim koneksi As New SqlClient.SqlConnection()
Dim koneksidatabase As String = "server=DESKTOP-KJQ8PNO\SQLEXPRESS;database=otto;Integrated Security=True"
koneksi.ConnectionString = koneksidatabase
koneksi.Open()
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet()
Dim dt As New DataTable
ds.Tables.Add(dt)
da = New OleDb.OleDbDataAdapter(query_excel, koneksi_excel)
da.Fill(dt)
Using bulkcopy As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(koneksi)
bulkcopy.DestinationTableName = file
bulkcopy.BulkCopyTimeout = 600
bulkcopy.WriteToServer(rd)
rd.Close()
MsgBox("Data uploaded to database", MsgBoxStyle.Information, "Uploaded")
TextBox1.Text = ""
End Using
End Sub

If you're using a DataGridView or some other grid to view the data, this is one way that you can view the data and load it into the grid.
Using ofd As New OpenFileDialog
ofd.InitialDirectory = dir
ofd.Filter = "Excel Files (*.xlsx)|*.xlsx| XLS Files (*.xls)|*.xls"
ofd.FilterIndex = 1
If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
txtFile.Text = ofd.FileName
fi = New FileInfo(ofd.FileName)
fileName = ofd.FileName
excel = fi.FullName
eCon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
excel & ";Extended Properties='Excel 12.0;IMEX=1;';")
eCon.Open()
Dim dtSheets As DataTable = eCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
If drSheet.Item("TABLE_NAME").ToString() <> "Sheet1$" Then
listSheet.Add(drSheet("TABLE_NAME").ToString())
Else
End If
Next
Me.Cursor = Cursors.WaitCursor
Dim myTable = ""
myTable = listSheet.Item(0)
da = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", myTable), eCon)
ds = New DataSet
da.Fill(ds, myTable)
Dim dt As DataTable = ds.Tables(0).Copy()
From here, set the dt as the grid DataSource. This way you know you're always getting the first worksheet, and don't have to worry about what the name is as such, the program is getting it for you.
Have a play around a let me know. Alternatively, you can just use this code to get the Excel sheet and use what you have already for the import.

Related

Import and Export csv File from DataGridView

High there, I'm currently making a small piece of software for a college project, The goal of the project is for the user to import ingredients and infomration and then they can create meals with these ingredients.
I'm having an issue though where when I load my csv file in after I've used the software once to add in a new ingredient I get the error: "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" and it highlights the section of the code "newRow("Protien") = columns(1)" Now I think is because when it loads in the data from the recently saved csv file it has a row at the top that is filled with the headers, is there any way that I can save the csv file without including the headers from the data table?
Code that laods in the csv file:
'Sets up the data table that will be used to store the ingredients and their information.'
With ingredientTable
.Columns.Add("Name", System.Type.GetType("System.String"))
.Columns.Add("Protien", System.Type.GetType("System.Decimal"))
.Columns.Add("Fat", System.Type.GetType("System.Decimal"))
.Columns.Add("Salt", System.Type.GetType("System.Decimal"))
.Columns.Add("Carbs", System.Type.GetType("System.Decimal"))
.Columns.Add("Calories", System.Type.GetType("System.Decimal"))
End With
'Loads in the information from the CSV file to display all the previouly saved ingredients'
Dim fileReader As New IO.StreamReader("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", System.Text.Encoding.Default)
Dim ingredientString As String = ""
Do
ingredientString = fileReader.ReadLine
If ingredientString Is Nothing Then Exit Do
'Reads what is on the CSV file and sets up the columns and the rows.'
Dim columns() As String = ingredientString.Split(",")
Dim newRow As DataRow = ingredientTable.NewRow
newRow("Name") = columns(0)
newRow("Protien") = columns(1)
newRow("Fat") = columns(2)
newRow("Salt") = columns(3)
newRow("Carbs") = columns(4)
newRow("Calories") = columns(5)
ingredientTable.Rows.Add(newRow)
Loop
fileReader.Close()
DataGridView1.DataSource = ingredientTable
Me.Text = ingredientTable.Rows.Count & "rows"
Code that saves the CSV file:
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
#Region "Save ingredients"
Dim csvFile As String = String.Empty
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
'Used to ge the rows
For Each row As DataGridViewRow In DataGridView1.Rows
'Used to get each cell in the row
For Each cell As DataGridViewCell In row.Cells
csvFile = csvFile & cell.FormattedValue & ","
Next
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
Next
My.Computer.FileSystem.WriteAllText("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", csvFile, False)
#End Region
Here are a few options to consider, for loading data from a CSV to a DGV.
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
End Class
You must try this code.
OpenButton
Dim OpenFileDialog1 As New OpenFileDialog()
Dim constr As String
Dim con As OleDb.OleDbConnection
Try
OpenFileDialog1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm;"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Me.txtOpen.Text = OpenFileDialog1.FileName
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDb.OleDbConnection(constr)
con.Open()
cboSheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
cboSheet.DisplayMember = "TABLE_NAME"
cboSheet.ValueMember = "TABLE_NAME"
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Load Button
Dim constr As String
Dim dt As DataTable
Dim con As OleDbConnection
Dim sda As OleDbDataAdapter
Dim row As DataRow
Try
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDbConnection(constr)
sda = New OleDbDataAdapter("Select * from [" + cboSheet.SelectedValue + "]", con)
dt = New DataTable
sda.Fill(dt)
For Each row In dt.Rows
DataGridView3.DataSource = dt
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I hope it will works! :)

Import excel worksheet into vb.net

I have got an excel worksheet which actually calculates the loan... If we input the amount and no. of years,it gives us a list of all the EMI's to be made in the coming years.
My boss wants to integrate that excel worksheet into vb.net form....How can I do so? Please help me....
In your form add a DataGrid "GridControl1" and a button "BtnImport_Click :
In your button BtnImport_Click add this code
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
Dim dialog As New OpenFileDialog()
dialog.Filter = "Excel files |*.xls;*.xlsx"
dialog.InitialDirectory = "C:\"
dialog.Title = "Veuillez sélectionner le fichier à importer"
'Encrypt the selected file. I'll do this later. :)
If dialog.ShowDialog() = DialogResult.OK Then
Dim dt As DataTable
dt = ImportExceltoDatatable(dialog.FileName)
GridControl1.DataSource = dt
GridControl1.Visible = True
MsgBox(" done ! ", MsgBoxStyle.Information)
End If
End Sub
And add this function in your form :
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName) ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
Hop that help you

Why Excel Data not displayed complete in DataGrid in VB.NET?

I'm developing my app in VB.Net with the source below but the problem that I got, was the data not displayed completely in DataGridView.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As OleDb.OleDbConnection
Dim dta As OleDb.OleDbDataAdapter
Dim dts As DataSet
Dim excelpath As String
Dim ExcelQuery As String = "Select * From [IOT_NOVA$B12:S257]"
Try
If TextBox1.Text = "" Then
MsgBox("Please select Excel file to upload!", vbExclamation)
Exit Sub
End If
excelpath = TextBox1.Text
conn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelpath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';")
dta = New OleDb.OleDbDataAdapter(ExcelQuery, conn)
DtSet = New DataTable
dta.Fill(DtSet)
DataGridView1.DataSource = DtSet
conn.Close()
conn.Dispose()
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
End Try
End Sub
You need to set the table name when setting the DataSource of the DataGridview.
DataGridView1.DataSource = DtSet.Tables(0)
or
DataGridView1.DataSource = DtSet.Tables("IOT_NOVA")
You may have (had) an issue with default column box sizes.
See this question:
How to set max length of datagridview column
Edit: found another issue - excel data driver is buggy.
Look far down in this thread:
How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

Save/open OLE object from .mdb in vb winform

I am trying to add a feature to my vb winform program where a user can attach files (.doc, .docx, .jpg, .pdf) to a mdb file that holds other text data. The binary file and the file name are stored in the DB. The file name with path is passed as variable 'fpath'. below is what I have thus far (It is now working, meaning it saves the file name and binary data). Now, how can the user open the saved file? And, if it is a .doc or PDF etc, how do I make the default associated program open it? . Can someone help me with the rest?
Here is the code to store the OLE object:
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'data connection
Dim cn As New OleDb.OleDbConnection
cn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" & _
Application.StartupPath & "\data.mdb"
cn.Open()
'file name without path
Dim flName As String = filename.Text
'open file from the disk (file path is the path to the file to be opened)
Using fileStream As FileStream = File.OpenRead(fpath)
'create new MemoryStream object
Dim memStream As New MemoryStream()
memStream.SetLength(fileStream.Length)
'read file to MemoryStream
fileStream.Read(memStream.GetBuffer(), 0, CInt(Fix(fileStream.Length)))
Dim strImage As String = "?"
Dim arr As Byte()
arr = memStream.GetBuffer
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = cn
cmd.CommandText = "INSERT INTO tblstudent(name, photo) VALUES( ?, ?)"
cmd.Parameters.Add("#name", OleDbType.Char).Value = flName
cmd.Parameters.Add("#photo", OleDb.OleDbType.Binary).Value = arr
cmd.ExecuteNonQuery()
MsgBox("Data save successfully!")
cn.Close()
End Using
End Sub
After two weeks of searching and trying a bunch of methods, I got it to work. The code above is corrected and working for uploading a file to a .mdb file. The code below will retrieve it. Yes, I know saving files to a mdb is not the best, but there will only be a couple docs or pdf, and I need it all in one file for easy sharing between users.
Private Builder As New OleDbConnectionStringBuilder With _
{ _
.DataSource = IO.Path.Combine(Application.StartupPath & "\data.mdb"), _
.Provider = "Microsoft.Jet.OleDb.4.0" _
}
Private Sub btnGetfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetfile.Click
Dim selfile As String = fileDgv.CurrentCell.Value.ToString
Dim cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Dim cmd As New OleDbCommand With _
{ _
.Connection = cn, _
.CommandText = "SELECT photo FROM tblstudent WHERE name='" & selfile & "'" _
}
Dim NoDataList As New List(Of String)
Dim dr As OleDbDataReader = Nothing
Dim FileStream As System.IO.FileStream
Dim Reader As OleDbDataReader
Dim Data() As Byte = Nothing
Dim Writer As System.IO.BinaryWriter = Nothing
Dim bufferSize As Integer = 1000
Dim buffer(bufferSize - 1) As Byte
Dim startIndex As Long = 0
Dim numberOfBytes As Long = 0
cn.Open()
Reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
Reader.Read()
FileStream = New System.IO.FileStream(
IO.Path.Combine("C:\temp3", "temp", selfile),
System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
Writer = New System.IO.BinaryWriter(FileStream)
Do
numberOfBytes = Reader.GetBytes(0, startIndex, buffer, 0, bufferSize)
If numberOfBytes = 0 Then
Exit Do
End If
Writer.Write(buffer, 0, CInt(Fix(numberOfBytes)))
startIndex += numberOfBytes
Loop While True
Writer.Flush()
If Writer IsNot Nothing Then
Writer.Close()
End If
If FileStream IsNot Nothing Then
FileStream.Close()
End If
If Reader IsNot Nothing Then
Reader.Close()
End If
cn.Close()
MessageBox.Show("Done")
End Sub

selecting in vb.net with ms access database

I want to select some data in my table and I use this code :
Public Class frmLogin
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim t As New DataTable
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim cmd As OleDbCommand
Dim reader As OleDbDataReader = Nothing
Dim tuser As String = txtUsername.Text
Dim sql As String = "SELECT * FROM dosen WHERE nip=tuser"
Try
cmd = New OleDbCommand(sql, conn)
reader = cmd.ExecuteReader()
While reader.Read
MessageBox.Show(reader.GetString(0).ToString & _
vbTab & vbTab & reader.GetString(1).ToString)
End While
Finally
If reader IsNot Nothing Then reader.Close()
End Try
End Sub
But there is an error in reader = cmd.ExecuteReader() line. Anyone can help me?
Correct the mistakes. The code should be
Dim reader As OleDbDataReader ' no need for nothing
Dim adapter As New OleDbDataAdapter()
Dim sql As String = "SELECT * FROM dosen WHERE nip='" & tuser & "'"
tuser is a variable, not the content