如何将带有访问数据库的Datagridview导出到CSV文件?

时间:2019-07-25 17:02:36

标签: vb.net winforms csv ms-access datagridview

我想以.cvs或.txt格式导出

但是我不知道该怎么做

使用Datagridview并访问

这是将数据库调用到DataGridView的代码

Imports System.Data.OleDb
Imports System.IO

Public Class Form1


    Private Access As New DBControl
    Private Function NotEmpty(text As String) As Boolean
        Return Not String.IsNullOrEmpty(text)
    End Function

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Run Query
        Access.ExecQuery("SELECT * FROM Members ORDER BY username ASC")
        If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub

        'Fill DataGrid
        dgvData.DataSource = Access.DBDT





    End Sub
End Class

这是我的联系

Imports System.Data.OleDb


Public Class DBControl

    'Create or database Connection
    Private DbCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
        "Data Source=Sample.accdb")
    'Prepare DB Connect
    Private DBCmd As OleDbCommand

    'DB Data

    Public DBDA As OleDbDataAdapter
    Public DBDT As DataTable


    'Query Parameters

    Public Params As New List(Of OleDbParameter)

    'Query Statistics

    Public RecordCount As Integer
    Public Exception As String

    Public Sub ExecQuery(Query As String)
        'Reset Query Stats
        RecordCount = 0
        Exception = ""

        Try
            'Open A Connection 
            DbCon.Open()

            'Create DB Command
            DBCmd = New OleDbCommand(Query, DbCon)

            'Load Params into DB Command

            Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))

            'Clear params list

            Params.Clear()

            'Execute command & fill database

            DBDT = New DataTable
            DBDA = New OleDbDataAdapter(DBCmd)
            RecordCount = DBDA.Fill(DBDT)


        Catch ex As Exception

            Exception = ex.Message

        End Try

        'CLOSE YOUR CONNECTION
        If DbCon.State = ConnectionState.Open Then DbCon.Close()
    End Sub
    'INCLUDE QUERY & COMMAND PARAMETERS

    Public Sub AddParam(Name As String, value As Object)
        Dim NewParam As New OleDbParameter(Name, value)
        Params.Add(NewParam)

    End Sub



End Class

这是一种表单,如果您单击“导出”按钮,程序将以.csv或txt格式导出所有数据。

1 个答案:

答案 0 :(得分:0)

这就是我的方法...

Imports System.IO
Imports System.Windows.Forms
Imports excel = Microsoft.Office.Interop.Excel
Imports System.Data

---程序

Friend Sub ExportToCSV(ByVal strExportFileName As String,
                                 ByVal tmpDataGridView As DataGridView,
                                 Optional ByVal WriteColumnHeaders As Boolean = False,
                                 Optional ByVal strDelimiterType As String = ",",
                                 Optional ByVal OpenFile As Boolean = False)

        Try

            callingForm.prog.Maximum = tmpDataGridView.Rows.Count * tmpDataGridView.Columns.Count
            callingForm.lblProgInfo.Text = "Exporting data..."
            callingForm.prog.Visible = True
            callingForm.lblProgInfo.Visible = True

            callingForm.Refresh()
            callingForm.lblProgInfo.Refresh()

            '* Parameters Description:
            '* --------------------------------------------------------------
            '* strExportFileName = The name of the file to export to.

            '* DataGridView = The name of the DataGridView on your form.

            '* blnWriteColumnHeaderNames = YES/NO for writing the column
            '*  names as the first line of the CSV file.  This will cause
            '*  programs like Excel to argue but still open the file.

            '* strDelimiterType = The type of delimiter you want to use.
            '*  Examples:  TAB (vbTab) or Comma (",")
            '* --------------------------------------------------------------

            '* Create a StreamWriter object to open and write contents
            '* of the DataGridView columns and rows.
            Dim sr As StreamWriter = File.CreateText(strExportFileName)

            '* Create a variable to hold the delimiter type 
            '* (i.e., TAB or comma or whatever you choose)
            '* The default for this procedure is a comma (",").
            Dim strDelimiter As String = strDelimiterType

            '* Create a variable that holds the total number of columns
            '* in the DataGridView.
            Dim intColumnCount As Integer = tmpDataGridView.Columns.Count - 1

            '* Create a variable to hold the row data
            Dim strRowData As String = ""

            '* Create a variable to hold the row data from a combobox Cell
            Dim curValue As String = ""

            '* If the CSV file will have column names then write that data
            '* as the first line of the file.
            If WriteColumnHeaders Then

                '* Interate through each column and get/write the column name.
                For intX As Integer = 0 To intColumnCount

                    '* The If statement will not put a delimiter after the 
                    '* last value added.

                    '* The Replace function will remove the delimiter
                    '* from the field data if found.
                    strRowData += Replace(tmpDataGridView.Columns(intX).HeaderText, strDelimiter, "") & _
                    If(intX < intColumnCount, strDelimiter, "")

                Next intX

                '* Write the column header data to the CSV file.
                sr.WriteLine(strRowData)

            End If '* If blnWriteColumnHeaderNames

            '* Now collect data for each row and write to the CSV file.
            '* Loop through each row in the DataGridView.
            For intX As Integer = 0 To tmpDataGridView.Rows.Count - 1

                '* Reset the value of the strRowData variable
                strRowData = ""

                For intRowData As Integer = 0 To intColumnCount

                    If TypeOf (tmpDataGridView.Rows(intX).Cells(intRowData)) Is DataGridViewComboBoxCell Then
                        curValue = GetDisplayValueFromComboBoxCell(CType(tmpDataGridView.Rows(intX).Cells(intRowData), DataGridViewComboBoxCell))
                    Else
                        If tmpDataGridView.Rows(intX).Cells(intRowData).Value IsNot Nothing Then
                            curValue = tmpDataGridView.Rows(intX).Cells(intRowData).Value.ToString
                        Else
                            curValue = ""
                        End If

                    End If
                    '* The If statement will not put a delimiter after the 
                    '* last value added.

                    '* The Replace function will remove the delimiter
                    '* from the field data if found.
                    If Not IsDBNull(curValue) Then
                        strRowData += Replace(curValue, strDelimiter, "") & _
                            If(intRowData < intColumnCount, strDelimiter, "")
                    Else
                        strRowData += "" & If(intRowData < intColumnCount, strDelimiter, "")
                    End If
                    callingForm.prog.Value += 1
                    callingForm.prog.Refresh()
                Next intRowData

                '* Write the row data to the CSV file.
                sr.WriteLine(strRowData)

            Next intX

            '* Close the StreamWriter object.
            sr.Close()

            '* You are done!
            If OpenFile Then
                Process.Start(strExportFileName)
            Else
                MsgBox("Grid was successfully exported to this location:" & vbNewLine & strExportFileName, MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Grid Exported Successfully")
            End If
        Catch ex As Exception
            Err.Raise(Err.Number, "PrintExportDataGridView Object - " & Err.Source, "PrintExportDataGridView - ExportToCSV Failed - " & Err.Description)
        Finally
            callingForm.prog.Visible = False
            callingForm.lblProgInfo.Visible = False

        End Try

    End Sub

enter image description here