如需转载分享,请标明出处,且不用于盈利为目的,谢谢合作!
使用注解Bean的方式将List类型数据生成csv文件
1.添加pom.xml依赖
<!--opencsv-->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.6</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.新建类DataToCSV.java
package com.yss.file.filedown.util;
import com.opencsv.CSVWriter;
import com.opencsv.bean.*;
import com.opencsv.bean.customconverter.ConvertSplitOnWhitespace;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* 使用注解Bean方式
* List<Student>类型数据生成csv文件
*/
public class DataToCSV {
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Student {
@CsvBindByName(required = true, column = "学号")
String id;
@CsvBindByName(column = "姓名")
String name;
@CsvBindByName(column = "年龄")
int age;
@CsvBindByName(column = "性别")
String sex;
@CsvBindByName(column = "生日")
@CsvDate("yyyy-MM-dd hh:mm:ss")
Date birthday;
@CsvCustomBindByName(converter = ConvertSplitOnWhitespace.class, column = "爱好")
List<String> hobbies;
}
/**
* src:定义下载的文件路径
*
* @param src
*/
public static void createCSV(String src) {
System.out.println("数据加载...");
List<Student> dataList = new ArrayList<>();
Student s1 = new Student("20140101", "张三", 22, "男", new Date(), Arrays.asList("eat", "drink", "girl"));
Student s2 = new Student("20140102", "李四", 22, "男", new Date(), Arrays.asList("eat", "money", "girl"));
Student s3 = new Student("20140103", "王五", 22, "男", new Date(), Arrays.asList("eat", "$", "girl"));
Student s4 = new Student("20140104", "赵敏", 22, "女", new Date(), Arrays.asList("eat", "money", "boy"));
Student s5 = new Student("20140105", "张无忌", 22, "男", new Date(), Arrays.asList("eat", "$", "girl"));
dataList.add(s1);
dataList.add(s2);
dataList.add(s3);
dataList.add(s4);
dataList.add(s5);
System.out.println("数据加载完成...");
OutputStreamWriter writer = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(src);
writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8"));
// 手动加上BOM标识
writer.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }));
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR).build();
beanToCsv.write(dataList);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
createCSV("D:\\test.csv");
}
}
3.数据结果