我有一个一维数组 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();
}
}
要将 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();
}
}
我是一名优秀的程序员,十分优秀!