A Programmers thoughts
Saving Listview as (.csv) file
It was easy for me to save a file on the database but saving a file as a (.csv) format is another issue for me before. Until I discover saving as a (.csv) format is just as simple as saving file on a database. All you just need to do on this is that to call the streamwriter to save the data as (.csv) format. I have here a sample codes below where the data the loaded on my listview was saved as (.csv) format. Hope you enjoy.
Private Sub SaveAsFile()
'They want to do a SaveAs, so find out what they want to name the file
Dim saveFileDialog As SaveFileDialog = New SaveFileDialog()
saveFileDialog.Title = "Save File" p>
saveFileDialog.Filter = "Files (*.csv)|*.csv|All Files (*.*)|*.*"
saveFileDialog.DefaultExt = "csv"
saveFileDialog.AddExtension = True
If saveFileDialog.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
filename = saveFileDialog.FileName
End If
Try
Dim csvFileContents As New System.Text.StringBuilder
Dim currentLine As String = String.Empty
'Write out the column names as headers for the csv file.
For columnIndex As Int32 = 0 To 0
currentLine &= (String.Format("mycolumn_name"))
Next
'Remove trailing comma
csvFileContents.AppendLine(currentLine.Substring(0, currentLine.Length))
currentLine = String.Empty
'Write out the data.
For Each item As ListViewItem In ListView1.Items
For Each subItem As ListViewItem.ListViewSubItem In item.SubItems
currentLine &= (String.Format("""{0}"",", subItem.Text))
Next
'Remove trailing comma
csvFileContents.AppendLine(currentLine.Substring(0, currentLine.Length - 1))
currentLine = String.Empty
Next
'Create the file.
Dim sw As New System.IO.StreamWriter(filename)
sw.WriteLine(csvFileContents.ToString)
sw.Flush()
sw.Dispose()
Catch ex As Exception
End Try
End Sub
| Print article | This entry was posted by shyguy on July 16, 2009 at 4:55 am, and is filed under Vb.net Code and Snippets. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |











about 1 year ago
And to open one file to place it in one Viewlist :S .. could you help me , for example the saved file i made with your code .. please help ..
about 1 year ago
hey , works for me the code but now i need to replace the info inside the Listview1 .. please help me how to do it ..
i added your code about how to save all info and works .. but i dont know how to open the data to place it in the listview again .. :S jo jo j o
about 1 year ago
sorry for the delayed reply. ok, i will make an article for that..thanks for visiting my site and reminding it.
about 8 months ago
nice…it works., hoping for another post about anything related in CSV to VB convertion, etc. godbless…
about 4 months ago
I didn’t understand the concluding part of your article, could you please explain it more?
about 4 months ago
@LilSnoop: Well it’s your prerogative now to explore more on it… Just do a simple trial & error.