我正在尝试创建一个新的 csv 文件,其中每个列将从不同的列表中获取值。 例如,第一列将包含第一个列表的所有值,第二列将包含第二个列表的所有值。
public void writeDataAtOnce()
{
File workingDirectory = new File(System.getProperty("user.dir"));
String path = workingDirectory + "/src/csv/";
String csvFile = path + "CsvOutput.csv";
try {
FileWriter outputfile = new FileWriter(csvFile);
CSVWriter writer = new CSVWriter(outputfile);
List<String[]> data = new ArrayList<>();
data.add(new String[] {String.valueOf(firstColumn)});
data.add(new String[] {String.valueOf(secondColumn)});
writer.writeAll(data);
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我设法逐行写入,但我需要写入列。 这是结果:
"A","B","C"
"35"
"19"
"33"
"31"
"25"
"45"
"16"
但是我想要做的是将第二个列表放在“B”列上。现在两个列表都在“A”列中 我该怎么做?
谢谢
最佳答案
如果两个列表的长度相等...
List<String> firstColumn = new ArrayList<>();
List<String> secondColumn = new ArrayList<>();
//TODO add data to lists
int size = firstColumn.size();
for (int i = 0; i < size; i++) {
data.add(new String[] {firstColumn.get(i), secondColumn.get(i)});
}
关于java - 如何将多个列表中的值写入新的 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57288140/