Private Sub exportCSV(ByRef sExportFileName As String)
Try
Dim sCSV As New List(Of String)
' get column headers
Dim sColHeaders As String = ""
For Each col As DataGridViewColumn In dgv.Columns
If col.Visible = True Then
Dim sCol As String = ""
sCol = col.HeaderText.ToString
If sCol.Contains(",") Then
sCol = """" + sCol + """"
End If
sColHeaders = sColHeaders + sCol + ","
End If
Next
sColHeaders = sColHeaders.Substring(0, sColHeaders.Length - 1)
' get row cell values
For Each row As DataGridViewRow In dgv.Rows
Dim sRow As String = ""
For Each cell As DataGridViewCell In row.Cells
If cell.Visible = True Then
Dim sValue As String = ""
If Not cell.Value Is Nothing Then
sValue = cell.Value.ToString
Else
sValue = ""
End If
If sValue.ToString.Contains(",") Then
sValue = """" + sValue + """"
End If
If sValue.ToString.ToUpper = "TRUE" Then
sValue = "Yes"
End If
If sValue.ToString.ToUpper = "FALSE" Then
sValue = "No"
End If
sRow = sRow + sValue + ","
End If
Next
sRow = sRow.Substring(0, sRow.Length - 1)
sCSV.Add(sRow)
Next
' write data to csv file
Using sw As New IO.StreamWriter(sExportFileName, False, System.Text.Encoding.UTF8)
sw.WriteLine(sColHeaders.ToString)
For Each s As String In sCSV
sw.WriteLine(s.ToString)
Next
End Using
If MessageBox.Show("CSV file created, open CSV file?", "Export Complete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
Process.Start(sExportFileName)
End If
Catch ex As Exception
MessageBox.Show(ex.ToString, "CSV Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.
”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.
Our community of experts have been thoroughly vetted for their expertise and industry experience.
The Distinguished Expert awards are presented to the top veteran and rookie experts to earn the most points in the top 50 topics.