导出Datagridview数据以访问数据库

时间:2019-07-14 07:12:12

标签: excel vb.net ms-access datagridview

我在vb.net中将所有表格从excel文件复制到datagridview。然后,我删除了datagrid视图中的某些列。现在,我希望将datagridview的新数据导出到已创建的访问数据库(.accdb)。

我搜索了互联网,但没有找到解决方法。

Imports System.Data.OleDb
Imports System.IO

Public Class epunjabdataimport
    Dim conn As OleDbConnection
    Dim dta As OleDbDataAdapter
    Dim dts As DataSet
    Dim excel As String
    Dim openfileDialog As New OpenFileDialog
    Private myConString As String
    Private cn1 As OleDbConnection = New OleDbConnection

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Try

            OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            openfileDialog.Filter = "Excel Files(*.xlsx)|*.xlsx"
            If openfileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
                Dim fi As New IO.FileInfo(openfileDialog.FileName)
                Dim FileName As String = openfileDialog.FileName
                excel = fi.FullName
                conn = New OleDbConnection("Provider=Microsoft.Ace.oledb.12.0;Data Source=" + excel + ";Extended Properties=Excel 12.0;")
                dta = New OleDbDataAdapter("Select * from [List_of_Student_Data$]", conn)
                '  dta = New OleDbDataAdapter("Select colmun3 as 'Student_Name', column4 as 'Father_Name', column10 as 'Class_Name', column11 as 'Section', Column21 as 'Admission_No', Column29 as 'Roll_No' from [List_of_Student_Data$]", conn)


                dts = New DataSet
                dta.Fill(dts, "[List_of_Student_Data$]")
                DataGridView1.DataSource = dts
                DataGridView1.DataMember = "[List_of_Student_Data$]"
                conn.Close()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try
        Try

            DataGridView1.Columns.RemoveAt(1)
            DataGridView1.Columns.RemoveAt(3)
            DataGridView1.Columns.RemoveAt(3)
            DataGridView1.Columns.RemoveAt(3)
            DataGridView1.Columns.RemoveAt(3)
            DataGridView1.Columns.RemoveAt(3)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)
            DataGridView1.Columns.RemoveAt(5)

            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)

            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)

            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(6)
            DataGridView1.Columns.RemoveAt(7)
            DataGridView1.Columns.RemoveAt(7)
            DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
            DataGridView1.Rows.Remove(DataGridView1.CurrentRow)

            With DataGridView1
                .RowHeadersVisible = False
                .Columns(0).HeaderCell.Value = "SNo"
                .Columns(1).HeaderCell.Value = "Student_Name"
                .Columns(2).HeaderCell.Value = "Father_Name"
                .Columns(3).HeaderCell.Value = "Class_Name"
                .Columns(4).HeaderCell.Value = "Section"
                .Columns(5).HeaderCell.Value = "Admission_No"
                .Columns(6).HeaderCell.Value = "Roll_No"
            End With
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub   

    Private Sub Epunjabdataimport_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim directory As String = My.Application.Info.DirectoryPath + "\callsec.accdb"
        myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + directory + "; Persist Security Info=False;"
        cn1.ConnectionString = myConString

    End Sub


End Class

我想要代码,以便单击按钮即可插入/导出datagridview的所有数据以访问数据库。

2 个答案:

答案 0 :(得分:0)

使用要保存的数据创建DataTable之后。 为上述适配器创建新的DataAdapter和CommandBuilder,然后简单地发送更新命令。由于没有先前的数据,它将把它当作数据库中指定表的新行。

一些伪代码:

 Adapter = New OleDb.OleDbDataAdapter("SELECT * FROM " & TableName, Database_Connection)
 DB_DataBuilder = New OleDb.OleDbCommandBuilder(Adapter)
 DB_DataBuilder.QuotePrefix = "["
 DB_DataBuilder.QuoteSuffix = "]"
 DB_Adapter.Update(DataTable)

如果还需要在数据库中创建表,则请打开与数据库的连接,并使用dbcomand“ CREATE TABLE”创建一个具有所选[列名]数据类型的表。

   DB_Connection.Open()
   Using cmd As New OleDb.OleDbCommand()
        cmd.Connection = DB_Connection
        cmd.CommandText = "CREATE TABLE [" & TableName & "]([Column1] TEXT, [Column2] DATETIME, [Column3] INTEGER)"
        Try
            cmd.ExecuteNonQuery()
            'MessageBox.Show("Table " & TableName & " created.")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Using
    DB_Connection.Close()

答案 1 :(得分:0)

在下面的示例中,您将在DataGridView和Access表之间加载,添加,保存和删除记录。

Imports System.Data.SqlClient
Public Class Form1
    Dim sCommand As SqlCommand
    Dim sAdapter As SqlDataAdapter
    Dim sBuilder As SqlCommandBuilder
    Dim sDs As DataSet
    Dim sTable As DataTable

    Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
        Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
        Dim sql As String = "SELECT * FROM Stores"
        Dim connection As New SqlConnection(connectionString)
        connection.Open()
        sCommand = New SqlCommand(sql, connection)
        sAdapter = New SqlDataAdapter(sCommand)
        sBuilder = New SqlCommandBuilder(sAdapter)
        sDs = New DataSet()
        sAdapter.Fill(sDs, "Stores")
        sTable = sDs.Tables("Stores")
        connection.Close()
        DataGridView1.DataSource = sDs.Tables("Stores")
        DataGridView1.ReadOnly = True
        save_btn.Enabled = False
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

    End Sub

    Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
        DataGridView1.[ReadOnly] = False
        save_btn.Enabled = True
        new_btn.Enabled = False
        delete_btn.Enabled = False
    End Sub

    Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
        If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
            sAdapter.Update(sTable)
        End If
    End Sub

    Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
        sAdapter.Update(sTable)
        DataGridView1.[ReadOnly] = True
        save_btn.Enabled = False
        new_btn.Enabled = True
        delete_btn.Enabled = True
    End Sub
End Class