[英]Write list into one column of a csv file
我需要一种关于如何将列表作为列写入 csv 文件的方法。
我有一个类,它的数据成员中存储了数据。 类看起来像这样
public class Final_object {
public String reporttype;
public List<String> metric_name=new ArrayList<String>();
public List<String> id=new ArrayList<String>();
public List<String> name=new ArrayList<String>();
public List<String> type=new ArrayList<String>();
}
我需要将每个列表作为一列写入 csv
使用Apache Commons CSV库,读取/写入各种CSV和制表符分隔格式的文件。
将此添加到您的班级应该可以完成这项工作:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
//...
public void writeCsv(String outputFilePath) throws IOException {
if(this.metric_name.size()!=this.id.size()
|| this.id.size()!=this.name.size()
|| this.name.size()!=this.type.size()) {
throw new IllegalStateException("ArrayLists backing CSV columns have mismatched size.");
}
try(CSVPrinter csv = new CSVPrinter(Files.newBufferedWriter(Paths.get(outputFilePath)), CSVFormat.DEFAULT)) {
//csv.printRecord("metric_name","id","name","type"); //uncomment if you want a header row
for (int i = 0; i < this.id.size(); i++) {
csv.printRecord(this.metric_name.get(i), this.id.get(i), this.name.get(i), this.type.get(i));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.