java csv 导入 导出 修改

来源:互联网 发布:淘宝碰到专业差评师 编辑:程序博客网 时间:2024/04/20 19:06



注:需要javacsv.jar


package csv;

import java.io.FileNotFoundException;
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;

public class csvTest {

 public static void main(String[] args) throws IOException {
       String filePath="d:/score.scv";
  //writeCsv(filePath);
  //readCsv(filePath);
  modifyCsv(filePath);
 }

 private static void modifyCsv(String filePath) throws IOException {
  List<String[]> list = new ArrayList<String[]>();
        CsvReader reader = new CsvReader(filePath,',',Charset.forName("GBK"));
        CsvWriter wr = new CsvWriter("d:/score1.scv",',',Charset.forName("GBK"));
        //reader.readHeaders();   // 跳过表头   如果需要表头的话,不要写这句。 
        while (reader.readRecord()) {    //逐行读入除表头的数据  
         list.add(reader.getValues());
   
  }
       
        for (int i = 0; i < list.size(); i++) {
         
   String[] cell =list.get(i);
   for (int j = 0; j < cell.length; j++) {
    
    cell[j]=cell[j]+j;
    System.out.println("cell---->"+cell[j]);
   }
   
   wr.writeRecord(cell);
  }
        wr.close();
 }

 private static void readCsv(String filePath) throws IOException {
  List<String[]> list = new ArrayList<String[]>();
        CsvReader reader = new CsvReader(filePath,',',Charset.forName("GBK"));
        reader.readHeaders();   // 跳过表头   如果需要表头的话,不要写这句。 
        while (reader.readRecord()) {    //逐行读入除表头的数据  
         list.add(reader.getValues());
   
  }
       
        for (int i = 0; i < list.size(); i++) {
         
   String[] cell =list.get(i);
   for (int j = 0; j < cell.length; j++) {
    System.out.println("cell---->"+cell[j]);
   }
   
  }
 }

 private static void writeCsv(String filePath) throws IOException {

  CsvWriter wr = new CsvWriter(filePath,',',Charset.forName("GBK"));
  String[] contents={"aaa","bbbbb","ddddd","eeeee"};
  wr.writeRecord(contents);
  wr.close();
  
 }

}

0 0