標籤:commons csv
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(); } } }}
apache commons csv寫檔案demo