Pixie Pixie - 1 year ago 61
Java Question

Store an ArrayList into a csv with the rows being every two elements

I have the following array in form of ArrayList in Java:

[a, b, c, d, e, f, ...]

I want to create a csv table with the following contents i.e. rows created with two cells every two elements:

enter image description here

For now that is what I have:

public static void writeExcel(ArrayList<String> arrayList) throws Exception {

BufferedWriter writer = null;

try {

writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src/Orders.csv"), "utf-8"));

for (code....)

writer.write(code ...)

} catch (IOException ex) {

} finally {

try {
} catch (Exception ex) {


Can somebody help me with the for loops?

Answer Source

The following loop will work:

List<String> arrayList = new ArrayList<String>();

int i = 0, size = arrayList.size();
while (i < size)
    String col1 = arrayList.get(i);
    String col2 = ",";
    if (i < size)
        col2 += arrayList.get(i);

    writer.write(col1 + col2);

    // put a new line here

    i++; // go to the next one
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download