【问题标题】:How can export the Datagridview with access database to CSV file?如何将带有 access 数据库的 Datagridview 导出到 CSV 文件?
【发布时间】:2019-07-25 17:02:36
【问题描述】:

我想以 .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 格式导出所有数据。

【问题讨论】:

  • 大概Access.DBDTSystem.Data.DataTable - 很确定有现成的Nuget 包接受DataTable 并让您将其内容转储到.csv 文件中。您将希望您的Export 按钮抓住dgvData.DataSource,将其转换为DataTable,然后从那里构建您的CSV。你坚持哪个具体部分?
  • 好吧,我卡在 Datagridview 中,假设我创建了一个按钮,上面写着 export 我想在按下按钮时将该数据导出到 .cvs

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


【解决方案1】:

这就是我的做法......

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

【讨论】:

  • 调用表单是做什么的?它说它没有声明
  • 调用表单可以是您想要呈现给用户的任何表单,其中包含网格。我在答案中添加了我的照片。
猜你喜欢
  • 2012-04-14
  • 2018-08-02
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 2013-04-08
  • 2012-12-22
相关资源
最近更新 更多