官网:http://opencsv.sourceforge.net/
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
import com.opencsv.bean.CsvBindByPosition;
import com.opencsv.bean.CsvCustomBindByPosition;
import com.opencsv.bean.customconverter.ConvertGermanToBoolean;
import io.searchbox.annotations.JestId;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@Accessors(chain = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SiteData implements Serializable {
@JestId
private String id;//唯一标志
@CsvBindByPosition(position = 0)
private String name;
@CsvBindByPosition(position = 1)
private String startTime;//开始时间
@CsvBindByPosition(position = 2)
private String endTime;//结束时间
@CsvBindAndSplitByPosition(position = 3,elementType = String.class, splitOn = "、")
private List<String> province;
@CsvBindByPosition(position = 4)
private String level;
@CsvBindByPosition(position = 5)
private String area;
@CsvCustomBindByPosition(position = 6 ,converter = ConvertGermanToBoolean.class)
private Boolean tripped;
@CsvBindByPosition(position = 7)
private String description;
}
@CsvBindByPosition(position = 1)
@CsvDate("yyyyMMdd")
private Date startTime;//开始时间
try {
InputStreamReader is = new InputStreamReader(new FileInputStream("E:\\hunan\\cc.csv"), "GBK");
// HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy();
// strategy.setType(SiteData.class);
List<SiteData> users = new CsvToBeanBuilder(is)
.withType(SiteData.class)
.withFilter(new SiteCsvToBeanFilter())
.withSeparator(',')
.withSkipLines(1)
// .withMappingStrategy(strategy) //
.build()
.parse();
System.out.println("users = " + new Gson().toJson(users));
} catch (Exception e) {
e.printStackTrace();
}
import com.opencsv.bean.CsvToBeanFilter;
public class SiteCsvToBeanFilter implements CsvToBeanFilter {
@Override
public boolean allowLine(String[] line) {
//若是第1列为空,则过滤掉
if (line[0].equals("")) {
return false;
}else{
return true;
}
}
}
接口名 | 策略 |
---|---|
MappingStrategy | 顶级的映射接口 |
headerColumnNameMappingStrategy | 基于列名的映射策略,读取csv文件的第一行作为header,比如header1,header2,header3 然后调用bean的setHeader1方法,setHeader2方法,setHeader3方法分别设置值。**所以这种策略要求,列名与bean中的属性名完全一致,如果不一致,则值为空,不会出错。使用注解时,注解名字必须与csv中列名一致。 |
ColumnPositionMappingStrategy | 列位置映射策略,他没有header的概念,所以会输出取所有行。在columnMapping数组中指定bean的属性,第一个值对应csv的第一列,第二个值对应csv的第二列…… |
HeaderColumnNameTranslateMappingStrategy | 列头名字翻译映射策略,与HeaderColumnNameMappintStrategy相比,bean的属性名可以与csv列头不一样。通过指定map来映射。 |