openCSV是一款简单的用于解析CSV文件的java类库,它封装了CSV格式文件的读写操作,可将文件与java对象进行自动映射,自定义分隔符,使用转义符等。
在使用时有几点需要注意下:
1、 生成的csv文件用EXCEL打开时,总是产生乱码,但是用NOTEPAD++打开时,显示正常。这是因为导出的文件是UTF-8不含BOM格式编码的,为了要让EXCEL正确的显示,需要手动的给将要输出的内容加上BOM标识。
2、 可通过@ CsvBindByName和@ CsvBindByPosition来CSV文件字段与对象属性进行映射。@ CsvBindByName是根据表头的名称来映射;@CsvBindByPosition是根据文件中字段的位置来映射。当2个注解一起使用时则基于位置的方式有效。因此如果写文件时即想指定顺序又想加表头的话需手动写表头。
3、 在读CSV文件时需要注意BOM字符,因为在写文件时为了能在Excel里打开增加了UTF-8 BOM标识,读文件时第一列会读不出来。这种情况的解决方法是使用apache commons io提供的BOMInputStream。
代码示例如下
public class Person {
private String name;
private int age;
private int sex;
private String phone;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return ":"+name + ";" + age + ";" + sex + ";" + phone + ";" + address;
}
}
public class WriteCSV {
public void writeCSV2(List<Person> dataList, String finalPath) {
try {
Writer writer = new FileWriter(finalPath);
// 手动加上BOM标识
writer.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }));
// 设置显示的顺序
String[] columnMapping = { "name", "age", "sex", "phone", "address" };
ColumnPositionMappingStrategy<Person> mapper =
new ColumnPositionMappingStrategy<Person>();
mapper.setType(Person.class);
mapper.setColumnMapping(columnMapping);
// 写表头
CSVWriter csvWriter = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR,
CSVWriter.NO_QUOTE_CHARACTER);
String[] header = { "姓名", "年龄", "性别", "手机", "住址" };
csvWriter.writeNext(header);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mapper)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withEscapechar('\\').build();
beanToCsv.write(dataList);
csvWriter.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
} catch (CsvDataTypeMismatchException e) {
e.printStackTrace();
} catch (CsvRequiredFieldEmptyException e) {
e.printStackTrace();
}
System.out.println(finalPath + "数据导出成功");
}
public void readCSV2(String finalPath) {
try {
// 使用BOMInputStream自动去除UTF-8中的BOM
Reader reader = new InputStreamReader(new BOMInputStream(
new FileInputStream(finalPath)), "utf-8");
CSVReader csvReader = new CSVReader(reader, CSVWriter.DEFAULT_SEPARATOR,
CSVWriter.NO_QUOTE_CHARACTER);
// 列名的映射
HeaderColumnNameTranslateMappingStrategy<Person> strategy =
new HeaderColumnNameTranslateMappingStrategy<Person>();
strategy.setType(Person.class);
Map<String, String> columnMapping = new HashMap<String, String>();
columnMapping.put("姓名", "name");
columnMapping.put("年龄", "age");
columnMapping.put("性别", "sex");
columnMapping.put("手机", "phone");
columnMapping.put("住址", "address");
strategy.setColumnMapping(columnMapping);
CsvToBean<Person> csvToBean = new CsvToBean<Person>();
List<Person> list = csvToBean.parse(strategy, csvReader);
for (Person p : list) {
System.out.println(p.toString());
}
csvReader.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
List<Person> dataList = new ArrayList<Person>();
Person person1 = new Person();
person1.setName("張三");
person1.setSex(1);
person1.setAge(55);
person1.setPhone("13911111111");
person1.setAddress("北京海淀区");
dataList.add(person1);
Person person2 = new Person();
person2.setName("小美");
person2.setSex(0);
person2.setAge(20);
person2.setPhone("13911112222");
person2.setAddress("北京西城区");
dataList.add(person2);
Person person3 = new Person();
person3.setName("小明");
person3.setSex(1);
person3.setAge(25);
person3.setPhone("13933333333");
person3.setAddress("北京海淀区");
dataList.add(person3);
WriteCSV writer = new WriteCSV();
String finalPath2 = "D:/bbb.csv";
writer.writeCSV2(dataList, finalPath2);
writer.readCSV2(finalPath2);
}
}