B4J Question How to save a mulitielement array as csv?

positrom2

Active Member
Licensed User
Longtime User
I am having an array a(n,199). For n=99, how to save it as a csv file so that I have 100 columns and 200 rows?
For n=3 for example, I can use
Code: Copy
For i=0 To 199
CSVlist.Add(Array As String(i,a(i,0),a(i,1),a(i,2),a(i,3)))
Next
su.SaveCSV("d:\",filename&".csv",",", CSVlist)
but for large n this becomes unhandy:(.
There is the hint that one could "add the array directly using Addall", but I can't figure it out.
 
To use add all you would need to be able to access the array with a single index to get a row, which is not possible.

You could build the string for each row before adding it.

Something like:

Code: Copy
    For i=0 To 199
        Dim LineStr As String = i&","
        For j = 0 To 99
            LineStr = LineStr & A(j,i)&","
        Next
        'Remove the last ","
        LineStr=LineStr.SubString2(0,LineStr.Length-1)
        CSVList.Add(LineStr)
    Next

You may want to enclose each item in quotes which is common practice and can save issues where the data string may contain a comma:

Code: Copy
    For i=0 To 199
        Dim LineStr As String = QUOTE&i&QUOTE&","
        For j = 0 To 99
            LineStr = LineStr & QUOTE&A(j,i)&QUOTE&","
        Next
        'Remove the last ","
        LineStr=LineStr.SubString2(0,LineStr.Length-1)
        CSVList.Add(LineStr)
    Next

Example attached
 

Attachments

Upvote 0
Hi Stevel,
thanks for your prompt answer, it works, (of course). But Stringutils to save as csv file did not like that LineStr list format, for whatever reason. However, I could use File.writelist(....,LineStr) directly.
Thanks.
 
Upvote 0
Ok, just checked, SUtils requires a list of arrays. So the code would need to be something like:

Code: Copy
For i=0 To 199
        Dim B(101) As String
        B(0) = i
        For j = 1 To 100
            B(j) = A(j-1,i)
        Next
        CSVList.Add(B)
    Next
 
Upvote 0

Similar Threads

Back
Top