'Pat Tormey Foursquare Solutions Inc. www.4square.net Jun 06
'Recommended for export to Excel as comma delimited
'Suggest Isolated Storage for File to avoid security and multi user issues..
'Note: Replaces existing commas with space.
Imports System.IO
Namespace Modules
Module modExportDataView
Sub ExportDataGridView(ByVal Filename As String, ByVal dgv As DataGridView)
Dim row As DataGridViewRow
Dim col As DataGridViewColumn
Dim sWriter As StreamWriter
Dim sValue As String
Try
sWriter = New StreamWriter(Filename, False)
Catch ex As System.IO.IOException
Throw New Exception(Filename & " is in Use") 'probably
Return
End Try
For Each col In dgv.Columns
If col.Visible Then
sWriter.Write(col.HeaderText)
If col.Index < dgv.Columns.Count Then
sWriter.Write(",")
End If
End If
Next 'col
sWriter.WriteLine()
For Each row In dgv.Rows
For Each col In dgv.Columns
If col.Visible Then
Try
If Not row.Cells(col.Index).Value Is Nothing Then
Select Case row.Cells(col.Index).ValueType.Name
Case "String"
sValue = CType(row.Cells(col.Index).Value, String)
sValue = Replace(sValue, ",", " ") 'lose the commas
sWriter.Write(sValue.Trim)
'Case Additional Formatting Not Implemented
Case Else
sWriter.Write(row.Cells(col.Index).Value)
End Select
End If 'row.Cells(col.Index).Value i snothing
If col.Index < dgv.Columns.Count Then sWriter.Write(",")
Catch ex As Exception
Throw New Exception("Something went wrong Exporting DatagridView")
End Try
End If 'Visible
Next 'Col
sWriter.WriteLine()
Next 'row
sWriter.Flush()
sWriter.Close()
End Sub
End Module
End Namespace
|