Monday, September 16, 2013

Read CSV or Excel file in VB.net and save it into SQL Server

Hello guys,
Today am going to write some important code for those who are beginners and want to learn VB.net..

if Any one need to export excel data or import Excel data in VB.net who can use this code...

---------------------- To Export Datagridview Value into Excel---------------------------------

Private sub Export
Try
           Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
            Dim wBook As Microsoft.Office.Interop.Excel.Workbook
            Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

         excel.Visible = True
            excel.UserControl = True
            wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
            wSheet = CType(wBook.Sheets("Sheet1"), Microsoft.Office.Interop.Excel.Worksheet)

           For Each column As DataGridViewColumn In dgv.Columns
                wSheet.Cells(1, column.Index + 1) = column.HeaderText
            Next
            For i = 0 To dgv.RowCount - 1
                For j = 0 To dgv.ColumnCount - 1
                    wSheet.Cells(i + 2, j + 1) = dgv.Rows(i).Cells(j).Value.ToString()
                Next j
            Next i
            wSheet.Columns.AutoFit()
           MsgBox("Data Exported Successfully.....")
            excel.Quit()
        Catch ex As Exception
            MsgBox("Error in Exporting.......  " & ex.Message)
        End Try

    End Sub

----------------------- To Save this data into SQLServer -----------------




Public con As New SqlConnection()

    Sub conn()
        If con.State = ConnectionState.Open Then
            con.Close()
        End If
        con.Open()
    End Sub

  Sub save()

        Try
            Dim gridcnt As Integer
            gridcnt = dgv.Rows.Count
            Dim cmd As New SqlCommand
        con.ConnectionString = "Data Source=Server;Initial Catalog = " & myfile & "; Integrated Security=True"
            'con.ConnectionString = "Data Source=Server; Integrated Security=True"
            conn()
            'cmd.CommandText = "CREATE DATABASE " & myfile
            'cmd.Connection = con
            'cmd.ExecuteNonQuery()
            'con.ConnectionString += "Initial Catalog=" & myfile & ";"

            btnSave1.Enabled = False
            Dim qry As String = "id int, "
            Dim qi As Integer = 0
            For Each col As DataGridViewColumn In dgv.Columns
                ' qry += dgv.Rows(0).Cells(qi).Value.ToString & " varchar(100), "
                qry += dgv.Columns(qi).Name.ToString & " varchar(100), "
                qi = qi + 1
            Next
            Dim newTable As String = "S" & myfile
            Dim i2 As Integer = qry.LastIndexOf(",")
            Dim qry2 As String = qry.Remove(i2, 1)
            cmd.CommandText = "DROP TABLE " & newTable
            cmd.Connection = con
            cmd.ExecuteNonQuery()
            cmd.CommandText = "CREATE TABLE " & newTable & " (" & qry2 & ");"
            cmd.Connection = con
            cmd.ExecuteNonQuery()
            Dim cnt As Integer = dgv.ColumnCount
            Dim c As Integer = dgv.Rows.Count
            Dim i, j, k As Integer
            Dim insert As String = "'1',"
            Dim insertqry As String = ""

            For i = 0 To c - 1
                For j = 0 To cnt - 1
                    If String.IsNullOrEmpty(dgv.Rows(i).Cells(j).Value.ToString()) Then
                        dgv.DefaultCellStyle.NullValue = "-"
                        'DataGridView1.Rows(i).Cells(j).ReadOnly = False
                        'DataGridView1.Rows(i).Cells(j).Value = "-"
                    End If

                    insert += "'" & dgv.Rows(i).Cells(j).Value.ToString() & "', "
                Next
                   Dim i3 As Integer = insert.LastIndexOf(",")
                Dim ins1 As String = insert.Remove(i3, 1)
                Dim ins As String = ins1.Replace("""", String.Empty)
                             k = i + 2
                insert = "'" & k & "',".ToString()
                cmd.CommandText = "INSERT INTO " & newTable & " VALUES (" & ins & ");"
                cmd.Connection = con
                cmd.ExecuteNonQuery()
            Next

           
            MsgBox("Data Saved in SQL Server Successfully.........")
            dgv.DataSource = Nothing
            MsgBox("Now Data Comes From SQL Server.........")
            fillbySQL()
            con.Close()
        Catch ex As Exception
            con.Close()
            MsgBox("Error in Saving .............. " & ex.Message)
        End Try
    End Sub

No comments:

Post a Comment