java - Is there an easy way to output a column-wise CSV? -
i'm trying output multiple lists of data, of varying length, csv file. each list should column in output csv file. there straight-forward way of doing thing? if outputting each list row, i'd loop on each list , output return when hit end, approach not work when working column-wise.
i thought of going on lists @ once, item item , incrementing counter, fail because lists longer others. remedy have check @ each iteration whether counter past end of each list, expensive in terms of computations.
thanks ideas!
i think pretty straight-forward:
public static void main(string... args) throws ioexception { arraylist<arraylist<string>> rows = getrandomdata(); if (rows.size() == 0) throw new runtimeexception("no rows"); // normalize data int longest = 0; (list<string> row : rows) if (row.size() > longest) longest = row.size(); (list<string> row : rows) while (row.size() < longest) row.add(""); if (longest == 0) throw new runtimeexception("no colums"); // fix special characters (int = 0; < rows.size(); i++) (int j = 0; j < rows.get(i).size(); j++) rows.get(i).set(j, fixspecial(rows.get(i).get(j))); // maximum size of 1 column int[] maxcolumn = new int[rows.get(0).size()]; (int = 0; < rows.size(); i++) (int j = 0; j < rows.get(i).size(); j++) if (maxcolumn[j] < rows.get(i).get(j).length()) maxcolumn[j] = rows.get(i).get(j).length(); // create format string string outformat = ""; (int max : maxcolumn) outformat += "%-" + (max + 1) + "s, "; outformat = outformat.substring(0, outformat.length() - 2) + "\n"; // print data (list<string> row : rows) system.out.printf(outformat, row.toarray()); } private static string fixspecial(string s) { s = s.replaceall("(\")", "$1$1"); if (s.contains("\n") || s.contains(",") || s.contains("\"") || s.trim().length() < s.length()) { s = "\"" + s + "\""; } return s; } private static arraylist<arraylist<string>> getrandomdata() { arraylist<arraylist<string>> data = new arraylist<arraylist<string>>(); string[] rand = { "do", "re", "song", "david", "test", "4", "hohjoh", "a \"h\" o", "tjo,ad" }; random r = new random(5); (int = 0; < 10; i++) { arraylist<string> row = new arraylist<string>(); (int j = 0; j < r.nextint(10); j++) row.add(rand[r.nextint(rand.length)]); data.add(row); } return data; }
output (pretty ugly since random) (escapes):
re , 4 , "tjo,ad" , "tjo,ad" , "tjo,ad" , "a ""h"" o" , , , re , "a ""h"" o" , hohjoh , "tjo,ad" , 4 4 , david , , , 4 , test , "tjo,ad" , hohjoh , re , hohjoh , test , , hohjoh , song , , , 4 , song , , , 4 , , song , , song , test , test , ,
Comments
Post a Comment