你的位置:首页 > Java教程

[Java教程]java操作csv文件之javacsv.jar应用


csv文件是分隔文件,如果使用java的io流来写,比较麻烦,这里为大家提供一个javacsv的jar包,这个很方便操作csv文件。

下载地址:https://pan.baidu.com/s/1i46ErFB

那如何使用呢?

只要看看以下一个例子,您一下就明白了。

 

 1 import com.csvreader.CsvReader; 2 import com.csvreader.CsvWriter; 3 import org.junit.Test; 4  5 import java.io.IOException; 6 import java.nio.charset.Charset; 7  8 /** 9  * Created by javalittleman on 2016/8/18.10 */11 public class TestCVS {12   /**13    * CSV导出14    *15    * @throws Exception16   */17   @Test18   public void exportCsv() throws IOException {19     String srcCSV = "F:/cnt_programa.csv";20     String targetFile = "F:/test.csv";21     CsvReader reader = new CsvReader(srcCSV, ',', Charset.forName("UTF-8"));22     CsvWriter write =new CsvWriter(targetFile,',',Charset.forName("UTF-8"));23     //各字段以引号标记24     write.setForceQualifier(true);25     //路过表头26     //r.readHeaders();27     //逐条读取记录,直至读完28     String[] header = {};29     while (reader.readRecord()) {30       //把头保存起来31       if (reader.getCurrentRecord()==0){32         header = reader.getValues();33       }34       //获取当前记录位置35       System.out.print(reader.getCurrentRecord() + ".");36       //读取一条记录37       System.out.println(reader.getRawRecord());38       String[] tmp = {reader.getValues()[0],reader.getValues()[1]};39       //修改记录,并只写入第一个字段和第二字段40       if (!header[1].equals(tmp[1]) && ("".equals(tmp[1])||tmp==null)){41         tmp[1]="空";42         write.writeRecord(tmp);43       }else{44         write.writeRecord(new String[]{reader.getValues()[0],reader.getValues()[1]});45       }46     }47     reader.close();48     write.close();49   }50 }

 

 

cnt_programa.csv文件:
"id","pid","no","serial","name","createtime""100000","","No100000","","公司新闻","2016/8/23 17:12:09""100001","","No100001","","热点资讯","2016/8/24 17:12:36""100046","100001","No100046","1","银行动态","2016/8/1 10:36:31""100052","100001","No100052","2","法律法规","2016/8/2 20:39:10""100088","100001","No100088","3","专业文库","2016/8/5 19:05:47"

 

test.csv
"id","pid""100000","空""100001","空""100046","100001""100052","100001""100088","100001"