更新:此答案中的代码适用于 Super CSV 1.52。 Super CSV 2.4.0 的更新代码示例可以在项目网站上找到:
http://super-csv.github.io/super-csv/index.html
SuperCSV 项目直接支持 CSV 单元格的解析和结构化操作。从http://super-csv.github.io/super-csv/examples_reading.html 你会发现例如
给定一个班级
public class UserBean {
String username, password, street, town;
int zip;
public String getPassword() { return password; }
public String getStreet() { return street; }
public String getTown() { return town; }
public String getUsername() { return username; }
public int getZip() { return zip; }
public void setPassword(String password) { this.password = password; }
public void setStreet(String street) { this.street = street; }
public void setTown(String town) { this.town = town; }
public void setUsername(String username) { this.username = username; }
public void setZip(int zip) { this.zip = zip; }
}
并且您有一个带有标题的 CSV 文件。我们假设以下内容
username, password, date, zip, town
Klaus, qwexyKiks, 17/1/2007, 1111, New York
Oufu, bobilop, 10/10/2007, 4555, New York
然后您可以创建 UserBean 的实例,并使用以下代码从文件第二行中的值填充它
class ReadingObjects {
public static void main(String[] args) throws Exception{
ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = inFile.getCSVHeader(true);
UserBean user;
while( (user = inFile.read(UserBean.class, header, processors)) != null) {
System.out.println(user.getZip());
}
} finally {
inFile.close();
}
}
}
使用以下“操作规范”
final CellProcessor[] processors = new CellProcessor[] {
new Unique(new StrMinMax(5, 20)),
new StrMinMax(8, 35),
new ParseDate("dd/MM/yyyy"),
new Optional(new ParseInt()),
null
};