[英]How can export the Datagridview with access database to CSV file?
I want to export in .cvs or .txt我想以 .cvs 或 .txt 格式导出
but I don't get it how to do this但我不明白该怎么做
with the Datagridview and access使用 Datagridview 和访问
This is the code to call the database to 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
This is my connection这是我的连接
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
it's a form and if you click in the 'export' button the program should export all the data in .csv or txt.它是一个表格,如果您单击“导出”按钮,程序应该以 .csv 或 txt 格式导出所有数据。
This is how I do it...我就是这样做的...
Imports System.IO
Imports System.Windows.Forms
Imports excel = Microsoft.Office.Interop.Excel
Imports System.Data
--- Procedure - - 程序
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.