1. 程式人生 > >Java對csv的操作

Java對csv的操作

讀取csv

com.csvreader.CsvReader

@Test
public void testReader() throws Exception {
    CsvReader r = new CsvReader("F://info.csv", ',', Charset.forName("GBK"));
    // 讀取表頭
    r.readHeaders();//先讀取表頭
    String[] headers = r.getHeaders();//獲取表頭的陣列
    System.out.println(Arrays.toString(headers));
    // 逐條讀取記錄,直至讀完
while (r.readRecord()) { // 讀取一條記錄 String rawRecord = r.getRawRecord(); System.out.println(rawRecord); } r.close(); }

結果

[編號, 姓名, 性別, 年齡]
001,小明,男,21
002,小紅,女,18

寫入csv

com.csvreader.CsvWriter

@Test
public void testWriter() throws Exception {
    CsvWriter wr = new
CsvWriter("F://info.csv", ',', Charset.forName("GBK")); // 寫表頭 String[] headers = {"編號","姓名","性別","年齡"}; wr.writeRecord(headers); // 寫內容 List<String[]> contents = new ArrayList<String[]>(); String[] row1 = { "001", "小明", "男", "21" }; String[] row2 = { "002", "小紅", "女", "18"
}; contents.add(row1); contents.add(row2); for (String[] row : contents) { wr.writeRecord(row); } wr.close(); }

結果
info.csv

2017.10.26–By HDNew