ProblemYou need to write data stored in an array to a comma-separated-values ( CSV) file. This is often done to provide input to Excel. SolutionSample 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. DiscussionIn 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 dataSee AlsoRecipe 8.10 is the reverse of this recipe. |