如何在 java 中使用 opencsv CSVWriter 在 csv 中写入对象列表
How to write list of objects in a csv using opencsv CSVWriter in java
我正在尝试将一些数据写入 csv。这是我正在尝试做的事情:
class Sample {
private String id;
private String type;
private String name;
private int value;
// getter-setter
}
实施
import com.opencsv.CSVWriter;
...
// code snippet
List<String> ids = getIds();
List<Sample> result = new ArrayList<>();
for (String id : ids) {
Sample sample = getSample(id);
result.add(sample);
}
//write result to csv
CSVWriter csvWriter = new CSVWriter(new FileWriter(filePath), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
// Not sure what to do next here.
我找不到太多关于将实例列表写入 csv 的信息。
更新:
我按照@Praveen、@dgg 在评论中的建议尝试了以下链接和代码,但我得到的是空的 csv 文件。
public void writeToCsv(String filePath, String[] header, List<Sample> samples) throws IOException {
try (FileWriter writer = new FileWriter(filePath)) {
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Sample.class);
mappingStrategy.setColumnMapping(header);
StatefulBeanToCsv<Sample> beanToCsv = new StatefulBeanToCsvBuilder<Sample>(writer)
.withMappingStrategy(mappingStrategy)
.withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
// todo: getting empty csv file. why? currently debugging.
beanToCsv.write(samples);
} catch (CsvRequiredFieldEmptyException e) {
e.printStackTrace();
} catch (CsvDataTypeMismatchException e) {
e.printStackTrace();
}
}
您可以使用 StatefulBeanToCsv
将对象列表映射到 csv 文件
try (FileWriter writer = new FileWriter("path/to/file.csv")) {
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Sample.class);
String[] columns = { "Id", "Type", "Name", "Value" };
mappingStrategy.setColumnMapping(columns);
StatefulBeanToCsv beanWriter = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
.build();
beanWriter.write(sampleList);
}
我实际上找到了一种使用 PrintWriter
编写它的更好方法,其中我的 bean 通过覆盖 java bean 中的 toString()
直接添加到 csv 中。这是我所做的:
public void writeToCsv(List<Sample> sampleList, String header) throws IOException {
PrintWriter writer = new PrintWriter("filepath/demo/sample.csv");
writer.println(header);
for (Sample sample : sampleList) {
writer.println(sample.toString());
}
writer.close();
}
豆子
class Sample {
private String id;
private String type;
private String name;
private int value;
// getter-setter
@Override
public String toString(){
StringBuilder dataBuilder = new StringBuilder();
appendFieldValue(dataBuilder, id);
appendFieldValue(dataBuilder, type);
appendFieldValue(dataBuilder, name);
appendFieldValue(dataBuilder, value);
return dataBuilder.toString();
}
private void appendFieldValue(StringBuilder dataBuilder, String fieldValue) {
if(fieldValue != null) {
dataBuilder.append(fieldValue).append(",");
} else {
dataBuilder.append("").append(",");
}
}
}
我正在尝试将一些数据写入 csv。这是我正在尝试做的事情:
class Sample {
private String id;
private String type;
private String name;
private int value;
// getter-setter
}
实施
import com.opencsv.CSVWriter;
...
// code snippet
List<String> ids = getIds();
List<Sample> result = new ArrayList<>();
for (String id : ids) {
Sample sample = getSample(id);
result.add(sample);
}
//write result to csv
CSVWriter csvWriter = new CSVWriter(new FileWriter(filePath), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
// Not sure what to do next here.
我找不到太多关于将实例列表写入 csv 的信息。
更新:
我按照@Praveen、@dgg 在评论中的建议尝试了以下链接和代码,但我得到的是空的 csv 文件。
public void writeToCsv(String filePath, String[] header, List<Sample> samples) throws IOException {
try (FileWriter writer = new FileWriter(filePath)) {
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Sample.class);
mappingStrategy.setColumnMapping(header);
StatefulBeanToCsv<Sample> beanToCsv = new StatefulBeanToCsvBuilder<Sample>(writer)
.withMappingStrategy(mappingStrategy)
.withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
// todo: getting empty csv file. why? currently debugging.
beanToCsv.write(samples);
} catch (CsvRequiredFieldEmptyException e) {
e.printStackTrace();
} catch (CsvDataTypeMismatchException e) {
e.printStackTrace();
}
}
您可以使用 StatefulBeanToCsv
将对象列表映射到 csv 文件
try (FileWriter writer = new FileWriter("path/to/file.csv")) {
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Sample.class);
String[] columns = { "Id", "Type", "Name", "Value" };
mappingStrategy.setColumnMapping(columns);
StatefulBeanToCsv beanWriter = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
.build();
beanWriter.write(sampleList);
}
我实际上找到了一种使用 PrintWriter
编写它的更好方法,其中我的 bean 通过覆盖 java bean 中的 toString()
直接添加到 csv 中。这是我所做的:
public void writeToCsv(List<Sample> sampleList, String header) throws IOException {
PrintWriter writer = new PrintWriter("filepath/demo/sample.csv");
writer.println(header);
for (Sample sample : sampleList) {
writer.println(sample.toString());
}
writer.close();
}
豆子
class Sample {
private String id;
private String type;
private String name;
private int value;
// getter-setter
@Override
public String toString(){
StringBuilder dataBuilder = new StringBuilder();
appendFieldValue(dataBuilder, id);
appendFieldValue(dataBuilder, type);
appendFieldValue(dataBuilder, name);
appendFieldValue(dataBuilder, value);
return dataBuilder.toString();
}
private void appendFieldValue(StringBuilder dataBuilder, String fieldValue) {
if(fieldValue != null) {
dataBuilder.append(fieldValue).append(",");
} else {
dataBuilder.append("").append(",");
}
}
}