我有一个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();
}
}
答案 0 :(得分:1)
要将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();
}
}
答案 1 :(得分: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();
}
}