Reputation: 137
I have a CSV files output from a software without headers,
I need to change the order of columns based on a config file
initial-column Final-Column 1 5 2 3 3 1
Any ideas how to go about this?
Upvotes: 1
Views: 448
Reputation: 38875
There is very very little to go on, such as how the config file works and what the data looks like.
Note that using the layout of {1, 5, 2, 3, 3, 1}
you arent just reordering the columns, that drops one (4) and duplicates columns 1 and 3.
Using some fake random data left over from this answer, this reads it in, then writes it back out in a a different order. You will have to modify it to take the config file into consideration.
Sample data:
Ndxn fegy n, 105, Imaypfrtzghkh, -1, red, 1501
Mfyze, 1301, Kob dlfqcqtkoccxwbd, 0, blue, 704
Xe fnzeifvpha, 328, Mnarhrlselxhcyby hq, -1, red, 1903
Dim csvFile As String = "C:\Temp\mysqlbatch.csv"
Dim lines = File.ReadAllLines(csvFile)
Dim outFile As String = "C:\Temp\mysqlbatch2.csv"
Dim data As String()
Dim format As String = "{0}, {4}, {1}, {2}, {2}, {0}"
Using fs As New StreamWriter(outFile, False)
For Each s As String In lines
' not the best way to split a CSV,
' no OP data to know if it will work
data = s.Split(","c)
' specifiy the columns to write in
' the order desired
fs.WriteLine(String.Format(format,
data(0),
data(1),
data(2),
data(3),
data(4),
data(5)
)
)
Next
End Using
This approach uses the format string and placeholder ({N}
) to control the order. The placeholders and array elements are all zero based, so {1, 5, 2, 3, 3, 1}
becomes {0, 4, 1, 2, 2, 0}
. Your config file contents could simply be a collection of these format strings. Note that you can have more args to String.Format()
than there are placeholders but not fewer.
Output:
Ndxn fegy n, red, 105, Imaypfrtzghkh, Imaypfrtzghkh, Ndxn fegy n
Mfyze, blue, 1301, Kob dlfqcqtkoccxwbd, Kob dlfqcqtkoccxwbd, Mfyze
Xe fnzeifvpha, red, 328, Mnarhrlselxhcyby hq, Mnarhrlselxhcyby hq, Xe fnzeifvpha
Splitting the incoming data on the comma (s.Split(","c)
) will work in many cases, but not all. If the data contains commas (as in some currencies "1,23") it will fail. In this case the seperator char is usually ";" instead, but the data can have commons for other reasons ("Jan 22, 2016" or "garden hose, green"). The data may have to be split differently.
Note: All the OPs previous posts are vba
related. The title includes VB.NET
and is tagged vb.net, so this is a VB.NET answer
Upvotes: 2