Is there a way to convert an excel file into a datatable (without using connection string), so i can show it in a gridview? I already tried something, but I'm getting a System.NullReferenceException and i don't know why. Here's what i did:
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
If File.Exists(OpenFileDialog1.FileName) Then
If Path.GetExtension(OpenFileDialog1.FileName).ToString = ".xlsx" Then
Dim workbook As Workbook
Dim resourceName As String = "IGExcel.Resources." & OpenFileDialog1.FileName
Using stream As Stream = Me.GetType().Assembly.GetManifestResourceStream(resourceName)
Try
Workbook.Load(stream)
Catch ex As System.NullReferenceException
End Try
End Using
Dim dataTable As New DataTable
Dim sheet As Worksheet = workbook.Worksheets(0)
Dim serviceExcel
For Each row As WorksheetRow In sheet.Rows
serviceExcel = New ISAACServiceExcel()
serviceExcel.AufPos = row.Cells(0).Value.ToString()
serviceExcel.UANR = row.Cells(1).Value.ToString()
serviceExcel.K_Art = row.Cells(2).Value.ToString()
serviceExcel.Ueberbegriff = row.Cells(3).Value.ToString()
serviceExcel.Benennung = row.Cells(5).Value.ToString()
serviceExcel.Einheit = row.Cells(6).Value.ToString()
serviceExcel.Einzelkosten = row.Cells(7).ToString()
serviceExcel.Anzahl = row.Cells(8).ToString()
serviceExcel.Komponente = row.Cells(9).ToString()
serviceExcel.Projektbeteiligter = row.Cells(11).ToString()
serviceExcel.Chefblattposition = row.Cells(13).ToString()
serviceExcel.Total = row.Cells(15).ToString()
Next
dataTable = serviceExcel
dgv1.DataSource = dataTable
I will try to convince you that there is nothing to fear from connection strings. Three little functions here and you are displaying your data. I would bet it is somewhat faster than interop also.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim XLPath = GetExcelPath()
If XLPath IsNot Nothing Then
Dim XLSheet = GetSheetName(XLPath)
Dim dt = ExcelToDataTable(XLPath, XLSheet)
DataGridView1.DataSource = dt
Else
MessageBox.Show("No acceptable file selected.")
End If
End Sub
Private Function GetExcelPath() As String
Dim XLPath As String
OpenFileDialog1.Filter = "Excel files (*.xlsx)|*.xlsx"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
XLPath = OpenFileDialog1.FileName
Return XLPath
End If
Return Nothing
End Function
Private Function GetSheetName(path As String) As String
Dim sn As String
Dim dt As DataTable
Using cn As New OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {path};Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';")
cn.Open()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
sn = dt(0)("Table_Name").ToString
Return sn
End Function
Private Function ExcelToDataTable(path As String, SheetName As String) As DataTable
Dim XLConStr = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {path};Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"
Dim dt As New DataTable
Using cn As New OleDbConnection(XLConStr),
cmd As New OleDbCommand($"Select * From [{SheetName}];", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Related
I'm trying to make an army list builder for a miniatures strategy game.
I'd like to know the correct method to read a SQL table cell value and to put it for each unit into a ComboBox.text field, but only into the field.
The ComBoBox collection items should not be modified (I need them to remain as it is). I just want the ComboBox.text value to be modified with the red framed value, and for each unit
For the record, currently, I read the others table informations and load them into the others ComboBoxes this way :
Private Sub TextBoxQuantitéUnités_Click(sender As Object, e As EventArgs) Handles TextBoxQuantitéUnités.Click
Dim connection As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select * from liste1 Order By index_unité"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
Dim reader As SqlDataReader = cmd.ExecuteReader
ComboBoxNomUnités.DataSource = dt
ComboBoxNomUnités.DisplayMember = "nom_unité"
ComboBoxTypeUnités.DataSource = dt
ComboBoxTypeUnités.DisplayMember = "type_unité"
ComboBoxAbréviationUnités.DataSource = dt
ComboBoxAbréviationUnités.DisplayMember = "abréviation_unité"
ComboBoxCoutTotal.DataSource = dt
ComboBoxCoutTotal.DisplayMember = "cout_unité"
connection.Close()
End Sub
Many thanks :-)
The ComboBox.text where I want to load the cell value
The table picture with the framed value I want to load into the cell
The original ComboBox collection I want to keep
EDIT 2 :
My table structure
Your function call
A short clip of the program in order to understand my problem
As you can see, the function seems good and when I check the ComboBoxQuality text during the execution, it seems good but for some reason, it don't change...
The others Comboboxes are sync as you can see on the upper code.
Thanks in advance...
EDIT 3:
The whole code as requested :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class FormOst
Public Function GetStringFromQuery(ByVal SQLQuery As String) As String
Dim CN = New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
CN.Open()
Dim StrSql As String = SQLQuery
Dim cmdReader As SqlCommand = New SqlCommand(StrSql, CN)
cmdReader.CommandType = CommandType.Text
Dim SdrReader As SqlDataReader = cmdReader.ExecuteReader(CommandBehavior.CloseConnection)
GetStringFromQuery = ""
Try
With SdrReader
If .HasRows Then
While .Read
If .GetValue(0) Is DBNull.Value Then
GetStringFromQuery = ""
Else
If IsDBNull(.GetValue(0).ToString) Then
GetStringFromQuery = ""
Else
GetStringFromQuery = .GetValue(0).ToString
End If
End If
End While
End If
End With
CN.Close()
Catch ex As Exception
MsgBox(SQLQuery, MsgBoxStyle.Exclamation, "Error")
End Try
End Function
Private Sub TextBoListeArmées_Click(sender As Object, e As EventArgs) Handles TextBoxListeArmées.Click
Dim connection As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select [nom_unité] + ' | ' + [abréviation_unité] as Unité, index_unité, abréviation_unité, type_unité, qualité_unité, cout_unité from liste1 Order By index_unité"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
ComboBoxNomUnités.DataSource = dt
ComboBoxNomUnités.DisplayMember = "Unité"
ComboBoxNomUnités.AutoCompleteMode = AutoCompleteMode.Append
ComboBoxNomUnités.AutoCompleteSource = AutoCompleteSource.ListItems
ComboBoxTypeUnités.DataSource = dt
ComboBoxTypeUnités.DisplayMember = "type_unité"
ComboBoxAbréviationUnités.DataSource = dt
ComboBoxAbréviationUnités.DisplayMember = "abréviation_unité"
ComboBoxCoutUnité.DataSource = dt
ComboBoxCoutUnité.DisplayMember = "cout_unité"
LabelListeChargéeVisible.Enabled = True
LabelListeChargée.Visible = True
connection.Close()
End Sub
Private Sub TextBoxQuantitéUnités_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBoxQuantitéUnités.KeyPress
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
Private Sub TextBoxQuantitéUnités_TextChanged(sender As Object, e As EventArgs) Handles TextBoxQuantitéUnités.TextChanged
Try
TextBoxCoutTotal.Text = (Decimal.Parse(TextBoxQuantitéUnités.Text) * Decimal.Parse(ComboBoxCoutUnité.Text)).ToString()
Catch ex As Exception
End Try
End Sub
Private Sub ButtonEffacer_Click(sender As Object, e As EventArgs) Handles ButtonEffacer.Click
TextBoxQuantitéUnités.Text = ""
ComboBoxNomUnités.Text = ""
ComboBoxTypeUnités.Text = ""
ComboBoxQualitéUnités.Text = ""
ComboBoxAbréviationUnités.Text = ""
ComboBoxCoutUnité.Text = ""
TextBoxCoutTotal.Text = ""
End Sub
Private Sub LabelListeChargéeVisible_Tick(sender As Object, e As EventArgs) Handles LabelListeChargéeVisible.Tick
LabelListeChargée.Visible = False
LabelListeChargéeVisible.Enabled = False
End Sub
Private Sub ComboBoxNomUnités_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBoxNomUnités.SelectionChangeCommitted
Try
'' TextBoxCoutTotal.Text = (Decimal.Parse(ComboBoxCoutUnité.SelectedItem.ToString) * Decimal.Parse(TextBoxQuantitéUnités.Text)).ToString
ComboBoxQualitéUnités.Text = GetStringFromQuery("SELECT qualité_unité FROM liste1 ORDER BY index_unité")
Catch ex As Exception
End Try
End Sub
End Class
Function for retrieving your data via sql query
Public Function GetStringFromQuery(ByVal SQLQuery As String) As String
Dim CN As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
CN.Open()
Dim StrSql As String = SQLQuery
Dim cmdReader As SqlCommand = New SqlCommand(StrSql, CN)
cmdReader.CommandType = CommandType.Text
Dim SdrReader As SqlDataReader = cmdReader.ExecuteReader(CommandBehavior.CloseConnection)
'SdrReader = cmdReader.ExecuteReader
GetStringFromQuery = ""
Try
With SdrReader
If .HasRows Then
While .Read
If .GetValue(0) Is DBNull.Value Then
GetStringFromQuery = ""
Else
If IsDBNull(.GetValue(0).ToString) Then
GetStringFromQuery = ""
Else
GetStringFromQuery = .GetValue(0).ToString
End If
End If
End While
End If
End With
CN.Close()
Catch ex As Exception
MsgBox(SQLQuery, MsgBoxStyle.Exclamation, "Error")
End Try
End Function
Retrieve data and put into your combo box text
ComboBox.Text = GetStringFromQuery("Enter Sql Query here")
Your sql query problem.
Your query select everything and you suppose to return the UOM that relate to your item
Private Sub ComboBoxNomUnités_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBoxNomUnités.SelectionChangeCommitted
Try
Dim Product as string = ComboBoxNomUnités.Text
ComboBoxQualitéUnités.Text = GetStringFromQuery("SELECT qualité_unité FROM liste1 Where Nom_Unité = '" & Product & "'")
Catch ex As Exception
End Try
End Sub
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! :)
I have manage to add the reportview to my visual studio 2015 project but my code is not working
here is the code:
Imports System.Data.OleDb
Imports Microsoft.Reporting.WinForms
Public Class FRMREPORTS
Dim CN As OleDbConnection = Nothing
Dim CM As OleDbCommand = Nothing
Dim CN_S As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FILECAB.accdb"
Dim SQL_S As String = ""
Dim UP_STR As String = ""
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GET_DATA()
LOAD_REPORT()
RVIEW.RefreshReport()
End Sub
Public Sub GET_DATA()
Try
Dim SQL_R As String = "SELECT * From ITEMS"
Dim CN As New OleDbConnection(CN_S)
Dim D_A As New OleDbDataAdapter(SQL_R, CN)
Dim DS As New DataSet()
CN.Open()
D_A.Fill(DS, "ITEM_TABLE")
CN.Close()
DG_ITMES.DataSource = DS.Tables("ITEM_TABLE")
'Dim RDS As ReportDataSource = New ReportDataSource("ITEM_TABLE", DS.Tables)
'RVIEW.LocalReport.DataSources.Add(RDS)
With DG_ITMES
.Columns(0).HeaderCell.Value = "ID"
.Columns(1).HeaderCell.Value = "Category"
.Columns(2).HeaderCell.Value = "Description"
.Columns(3).HeaderCell.Value = "Unit"
.Columns(0).Visible = False
.Columns(1).Width = 150
.Columns(2).Width = 300
.Columns(3).Width = 150
.Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
End With
SQL_R = Nothing
If CN.State = ConnectionState.Open Then CN.Close()
D_A = Nothing
DS = Nothing
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Public Sub LOAD_REPORT()
Try
RVIEW.LocalReport.DataSources.Clear()
Dim DT As New DataTable
With DT
.Columns.Add("ID")
.Columns.Add("Category")
.Columns.Add("Description")
.Columns.Add("Unit")
End With
For Each row As DataGridViewRow In DG_ITMES.Rows
DT.Rows.Add(row.Cells(0).Value, row.Cells(1).Value, row.Cells(2).Value, row.Cells(3).Value)
Next
Dim RDS As ReportDataSource = New ReportDataSource(DT.TableName, DT)
RVIEW.LocalReport.DataSources.Add(RDS)
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
End Class
When I run this one this what I get from the report view "The source of the report definition has not been specified"
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
Imports System
Imports System.Data.SqlClient
Imports System.IO
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Read the file and convert it to Byte Array
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
'Set the contenttype based on File Extension
Select Case ext
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes() As Byte = br.ReadBytes(fs.Length)
lblMessage.Text = bytes.ToString 'System.Text.Encoding.Unicode.GetString(bytes)
'insert the file into database
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
Try
con.Open()
Dim strQuery As String = "insert into uploadedImages (Name, ContentType, Data) values ('" & filename & "','" & contenttype & "','"
Dim bytesLength As Integer = bytes.Length - 1
For i As Integer = 0 To bytesLength
strQuery = strQuery & bytes(i)
Next
strQuery = strQuery & "')"
Dim cmd As New SqlCommand(strQuery)
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
con.Dispose()
End Try
' InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully" '& System.Text.ASCIIEncoding.ASCII.GetString(bytes)
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." & " Upload Image JPG or PNG formats"
End If
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function
' code to retrieve image
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes As String = CType(dt.Rows(0)("Data"), String)
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
' convert a string to a byte array
Dim encoding As New System.Text.UTF8Encoding()
Response.BinaryWrite(encoding.GetBytes(dt.Rows(0)("Data")))
Response.Flush()
Response.End()
End Sub
Protected Sub btn_download_Click(sender As Object, e As EventArgs) Handles btn_download.Click
Dim strQuery As String = "select Name, ContentType, Data from uploadedImages where id=12"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("12", SqlDbType.Int).Value = 1
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Sub
End Class
The image downloads but the file is corrupted , I think the problem is when retrieving the string from the database and turning it into bytes ... Appreciate any help