1. 程式人生 > >JAVA關於.CSV檔案的建立、讀、寫操作示例

JAVA關於.CSV檔案的建立、讀、寫操作示例

依賴:

<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->

<dependency>

    <groupId>net.sourceforge.javacsv</groupId>

    <artifactId>javacsv</artifactId>

    <version>2.0</version>

</dependency>

引用:

import com.csvreader.CsvReader;

import com.csvreader.CsvWriter;

建立檔案:

	public void createCSV_file(String filePath) throws IOException {
		File csvFile = new File(filePath);
		File parent = csvFile.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
                if(!csvFile.exists()){
	        	csvFile.delete();
	        }
		csvFile.createNewFile();
	}

寫檔案:

    public void writeHeadCSV_file(CsvWriter wr) throws IOException {
           // 寫檔案頭,即列標題
           // CsvWriter wr = new CsvWriter(filePath, ',', Charset.forName("GBK"));

           String[] contents = { "行號", "內容1", "內容2", "內容3"};
           wr.writeRecord(contents);

     }

/** 
      *寫CSV檔案
      * @param filePath 檔案路徑fileLoad+檔名fileName
      * @throws IOException
      */
    public void writeCSV_filenum(String filePath) throws Exception {
            // 建立檔案
           createCSV_file(filePath);
           
           CsvWriter wr = new CsvWriter(filePath, ',', Charset.forName("UTF-8"));
           // 寫檔案頭
           writeHeadCSV_file(wr);
           //寫檔案內容
           String[] contents1 = { "1", "",""};
           wr.writeRecord(contents1);
         
	for (int i = 0; i < 10; i++) {
		String[] contents2 = { String.valueOf(i + 2),"",""};
		wr.writeRecord(contents2);
	}

           wr.endRecord();

           wr.close();

     }

讀檔案:

/**
      * 讀CSV檔案內容
      *
      * @param filePath 檔案路徑fileLoad+檔名fileName
      * @throws IOException
      */
     public List readCSV_productCurrencyInfo(String filePath) throws IOException {
           List list = new ArrayList();
           CsvReader r = new CsvReader(filePath, ',', Charset.forName("UTF-8"));
           // 讀取表頭
           r.readHeaders();
           System.out.println("表格頭" + r.getHeader(0));// 第一列表格頭
           int iCount = r.getHeaders().length;
           // 逐條讀取記錄,直至讀完
           while (r.readRecord()) {
                // 讀取一條記錄
                System.out.println("表格內容" + r.getRawRecord());
                // 按列名讀取這條記錄的值
                Map<String, String> map = new HashMap<>();
                for (int i = 0; i < iCount; i++) {
                     map.put(r.getHeader(i), r.get(r.getHeader(i)));// 根據實際表格列名讀取
                }
                list.add(map);
           }
           r.close();

           return list;

     }