JAVA操作csv檔案(匯入匯出)__JAVA

來源:互聯網
上載者:User

CSV是逗點分隔檔(Comma Separated Values)的首字母英文縮寫,是一種用來儲存資料的純文字格式,通常用於試算表或資料庫軟體。在 CSV檔案中,資料“欄”以逗號分隔,可允許程式通過讀取檔案為資料重新建立正確的欄結構,並在每次遇到逗號時開始新的一欄。


1、csv檔案用文本開啟顯示為:

1,張三,男2,李四,男3,小紅,女

2、csv檔案用Excel開啟顯示為:



一、利用javacsv2.0操作csv檔案:

package com.iflytek.demo;import java.io.FileOutputStream;import java.io.IOException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;import com.csvreader.CsvReader;import com.csvreader.CsvWriter;/** * 利用javacsv2.0做匯入匯出csv檔案工具類<br/> *  *  * @author kpchen *  */public class CSVUtil {static char separator = ',';public static void main(String[] args) throws Exception {// 測試匯出String filePath = "D:/test.csv";List<String[]> dataList = new ArrayList<String[]>();for (int i = 0; i < 10; i++) {dataList.add(new String[] { "0" + i, "小明" + i, "java" + i });}exportCsv(dataList, filePath);// 測試匯入List<String[]> datas = importCsv(filePath);for (String[] strings : datas) {System.out.println(strings[0]);}}/** * java匯入csv檔案 *  * @param filePath *            匯入路徑 * @return * @throws Exception */public static List<String[]> importCsv(String filePath) throws Exception {CsvReader reader = null;List<String[]> dataList = new ArrayList<String[]>();try {reader = new CsvReader(filePath, separator, Charset.forName("GBK"));// 讀取表頭reader.readHeaders();// 逐條讀取記錄,直至讀完while (reader.readRecord()) {dataList.add(reader.getRawRecord().split(","));// // 下面是幾個常用的方法// 讀取一條記錄System.out.println(reader.getRawRecord());// 按列名讀取這條記錄的值System.out.println(reader.get(0));System.out.println(reader.get(1));System.out.println(reader.get(2));System.out.println(reader.get(3));}} catch (Exception e) {System.out.println("讀取CSV出錯..." + e);throw e;} finally {if (null != reader) {reader.close();}}return dataList;}/** * java匯出cvs檔案 *  * @param dataList *            資料集 * @param filePath *            匯出路徑 * @return * @throws Exception */public static boolean exportCsv(List<String[]> dataList, String filePath) throws Exception {boolean isSuccess = false;CsvWriter writer = null;FileOutputStream out = null;try {out = new FileOutputStream(filePath, true);writer = new CsvWriter(out, separator, Charset.forName("GBK"));for (String[] strs : dataList) {writer.writeRecord(strs);}isSuccess = true;} catch (Exception e) {System.out.println("產生CSV出錯..." + e);throw e;} finally {if (null != writer) {writer.close();}if (null != out) {try {out.close();} catch (IOException e) {System.out.println("exportCsv close Exception: " + e);throw e;}}}return isSuccess;}}

二、利用流操作csv檔案

package com.iflytek.demo;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.List;public class CSVUtil2 {public static void main(String[] args) {// 測試 匯出// List<String> dataList = new ArrayList<String>();// dataList.add("1,張三,男");// dataList.add("2,李四,男");// dataList.add("3,小紅,女");// boolean isSuccess = exportCsv(new File("D:/test.csv"), dataList);// System.out.println(isSuccess);// 測試 匯入List<String> dataList = importCsv(new File("D:/test.csv"));if (dataList != null && !dataList.isEmpty()) {for (String data : dataList) {System.out.println(data);}}}/** * 匯出 *  * @param file *            csv檔案(路徑+檔案名稱),csv檔案不存在會自動建立 * @param dataList *            資料 * @return */public static boolean exportCsv(File file, List<String> dataList) {boolean isSucess = false;FileOutputStream out = null;OutputStreamWriter osw = null;BufferedWriter bw = null;try {out = new FileOutputStream(file);osw = new OutputStreamWriter(out);bw = new BufferedWriter(osw);if (dataList != null && !dataList.isEmpty()) {for (String data : dataList) {bw.append(data).append("\r\n");}}isSucess = true;} catch (Exception e) {isSucess = false;} finally {if (bw != null) {try {bw.close();bw = null;} catch (IOException e) {e.printStackTrace();}}if (osw != null) {try {osw.close();osw = null;} catch (IOException e) {e.printStackTrace();}}if (out != null) {try {out.close();out = null;} catch (IOException e) {e.printStackTrace();}}}return isSucess;}/** * 匯入 *  * @param file *            csv檔案(路徑+檔案) * @return */public static List<String> importCsv(File file) {List<String> dataList = new ArrayList<String>();BufferedReader br = null;try {br = new BufferedReader(new FileReader(file));String line = "";while ((line = br.readLine()) != null) {dataList.add(line);}} catch (Exception e) {} finally {if (br != null) {try {br.close();br = null;} catch (IOException e) {e.printStackTrace();}}}return dataList;}}

源碼:http://pan.baidu.com/s/1nt1r7ap


參考:http://write.blog.csdn.net/postedit/49755535

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.