Recipe 8.9. Writing a Comma-Separated-Values File from a String Array


Problem

You need to write data stored in an array to a comma-separated-values ( CSV) file. This is often done to provide input to Excel.

Solution

Sample code folder: Chapter 08\CreateCSVFiles

Use the String class's Join() method to concatenate array contents into strings, using a comma as the character to insert at the join points. Then write the string or strings to a file using the WriteAllText() method provided by the My.Computer.FileSystem object.

Discussion

In many cases you'll have several data items that you want to appear in each of several rows of a spreadsheet. This is accomplished by separating each data item in each row with a comma, and separating the rows from each other using newline characters. The following code demonstrates various ways to accomplish this. headings is a string array containing three words. The Join() method concatenates this array into a single string with commas separating each word. To simplify the example, several more similar comma-separated strings are concatenated to the string, each separated with vbNewLine characters. The resulting string is written to a file named Test.csv in a single command using the My.Computer.FileSystem.WriteAllText() method:

 Dim result As New System.Text.StringBuilder Dim headings( ) As String = {"Alpha", "Beta", "Gamma"} Dim workText As String = String.Join(",", headings) ' ----- Prepare the raw data. workText &= vbNewLine workText &= "1.1, 2.3, 4.5" & vbNewLine workText &= "4.2, 7.9, 3.1" & vbNewLine workText &= "3.5, 2.2, 9.8" & vbNewLine ' ----- Convert it to CSV and save it to a file. Dim filePath As   String = _    My.Computer.FileSystem.CurrentDirectory & "\Test.csv" My.Computer.FileSystem.WriteAllText(filePath, workText, False) result.Append("File written: ") result.AppendLine(filePath) result.AppendLine( ) result.AppendLine("File contents:") result.Append(workText) MsgBox(result.ToString( )) 

The remaining lines of example code display the new Test.csv file contents, as shown in Figure 8-9.

Figure 8-9. Writing CSV files from array data


See Also

Recipe 8.10 is the reverse of this recipe.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net