1

我有一个 String[]要写入 CSV 文件的一维数组,然后在 Excel 等电子表格程序中查看。但是,此数组的大小/长度太大而无法容纳允许的列数,但足够小以容纳允许的行数。

那么,如何按列而不是按行编写?

我正在使用的当前代码:

import au.com.bytecode.opencsv.CSVWriter;

public class test {
    public static void main(String[] args) [
        CSVWriter writer2 = new CSVWriter(new FileWriter("testing.csv"), '\t');

        String[] string = new String[10];
        for(int i = 0; i < 10; i++) {
            string[i] = "Testing";
        }

        writer2.writeNext(string); //  !!EXPORTS AS ROW AND NOT A COLUMN!! //
        writer2.close();




    }
}
4

2 回答 2

1

要将 a 写入String[]文件,每个字符串在单独的行中,您不需要 CSVWriter ...普通旧的FileOutputStream就可以了

public static class test {
  public static void main(String[] args) throws UnsupportedEncodingException, IOException {
    String[] strings = new String[10];
    for (int i = 0; i < 10; i++) {
      strings[i] = "Testing";
    }

    OutputStream output = new FileOutputStream("testing.csv");
    try {
      for (String s : strings) {
        output.write(s.getBytes("UTF-8")); // don't rely on default encoding!
      }
    }
    finally {
      output.close();
    }
  }
}

但是,如果您真的想使用以下方式编写CSVWriter

public static class test {
  public static void main(String[] args) throws UnsupportedEncodingException, IOException {
    CSVWriter writer2 = new CSVWriter(new FileWriter("testing.csv"), '\t');

    String[] strings = new String[10];
    for (int i = 0; i < 10; i++) {
      strings[i] = "Testing";
    }

    String[] wrap = new String[1]; //probably saving on GC

    for (String s: strings) {
      wrap[0]=s;
      writer2.writeNext(wrap);
    }
    writer2.close();

  }

}
于 2013-09-13T11:57:33.767 回答
0

writeNext写入 1 行。如果你调用它两次,它会写 2 行,如果你调用它 10 次,它会写 10 行对吗?:)

编辑:好的,让我们试试这个:

public void writeLines(String[] array, CSVWriter writer) {
    for (final String oneElement : array) {
        writer.writeNext(new String[] {oneElement});
    }
}

现在您可以调用该writeLines方法来编写一堆行。如果我以你为例:

import au.com.bytecode.opencsv.CSVWriter;

public class test {
    public static void main(String[] args) {
        CSVWriter writer2 = new CSVWriter(new FileWriter("testing.csv"), '\t');

        String[] string = new String[10];
        for(int i = 0; i < 10; i++) {
            string[i] = "Testing";
        }

        writer2.writeLines(string); // This will write a column
        writer2.close();
    }
}
于 2013-09-13T12:00:04.930 回答