1.简介
csv处理开源的工具有不少,比如:super csv 和 Apache commons csv,本文使用Apache Commons csv,其提供了非常简单的接口来读写csv文件。
本文是针对csv文件的写示例。
2.依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.1</version>
</dependency>
3.pojo对象
将需要保存的数据映射到对象中,然后将该对象信息写入csv 文件中。
package test.csv;
import java.math.BigDecimal;
/**
* 城市房价模型
*
* Created by qunzer on 2015/3/3.
*/
public class CityPrice {
private Integer id;
private String city;
private BigDecimal price;
public CityPrice(Integer id, String city, BigDecimal price) {
this.id = id;
this.city = city;
this.price = price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
4.csv写入代码示例
package test.csv;
import com.google.common.collect.Lists;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
/**
* Created by qunzer on 2015/3/3.
*/
public class CsvFileWriter {
private static final String LINE_SEPARATOR = "\n";
private static final String[] File_HEAND = {"编号", "城市", "房价"};
/**
* 初始化数据,比如从数据库取值等
*
* @return
*/
private static List<CityPrice> preCityPriceData() {
List<CityPrice> cityPriceList = Lists.newArrayList();
CityPrice cityPrice = new CityPrice(1, "beijing", BigDecimal.valueOf(350000));
cityPriceList.add(cityPrice);
return cityPriceList;
}
/**
* 写入csv文件
*
* @param fileName 传入文件的路径,包含文件名
*/
private static void csvWriter(String fileName) {
FileWriter fileWriter;
CSVPrinter csvPrinter = null;
CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator(LINE_SEPARATOR);
try {
fileWriter = new FileWriter(fileName);
csvPrinter = new CSVPrinter(fileWriter, csvFormat);
csvPrinter.printRecord(File_HEAND);
for (CityPrice cityPrice : preCityPriceData()) {
List<String> cityPriceRecord = Lists.newArrayList();
cityPriceRecord.add(String.valueOf(cityPrice.getId()));
cityPriceRecord.add(cityPrice.getCity());
cityPriceRecord.add(String.valueOf(cityPrice.getPrice()));
csvPrinter.printRecord(cityPriceRecord);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (csvPrinter != null) {
csvPrinter.flush();
csvPrinter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
原文地址:http://blog.csdn.net/qunzer/article/details/44035651