CSV – Comma Separated Values, a simple tabular text format where items are separated with the separator character.
CSV is a very basic and common text format.
1,"Escaped, Item",2 2,"Escaped, Item",4 3,"Escaped, Item",6 4,"Escaped, Item",8 5,"Escaped, Item",10 6,"Escaped, Item",12 7,"Escaped, Item",14 8,"Escaped, Item",16 9,"Escaped, Item",18 10,"Escaped, Item",20
Like all other text formats, it is a mistake to try to parse it without a library as there are some nuances. For example items that include the separator character need to be enclosed with quotes. Also true for items with quotes, which need to be enclosed with quotes and the quote should be escaped with another quote.
There are two options to parse or generate CSV strings in B4X: with the internal StringUtils library, or a bit better, with the CSVParser class. The CSVParser class can handle non-UTF8 encoding and also some other edge cases.
Note that older versions of Microsoft Excel doesn’t properly support non-ASCII characters in CSV files.
Code to generate the above CSV with CSVParser class:
Dim Table As List Table.Initialize For i = 1 To 10 Dim row(3) As String row(0) = i row(1) = "Escaped, Item" row(2) = i * 2 Table.Add(row) Next Dim Parser As CSVParser Parser.Initialize Dim CSV As String = Parser.GenerateString(Table, ",") Log(CSV)
The most important point to understand is that each item in the Table list is a new array of strings.
Code to parse this CSV string:
Dim Parser As CSVParser Parser.Initialize Dim Table As List = Parser.Parse(CSV, ",", False) 'set to True to skip first line For Each row() As String In Table Dim number As Int = row(0) Dim item As String = row(1) Log(number) Next