使用Javacsv.jar的jar包操作csv文件的方法

时间:2021-05-19

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

下载地址:http://xiazai.jb51.net/201608/yuanma/javcsv(jb51.net).rar

那如何使用呢?

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

import com.csvreader.CsvReader;import com.csvreader.CsvWriter;import org.junit.Test;import java.io.IOException;import java.nio.charset.Charset;/*** Created by javalittleman on 2016/8/18.*/public class TestCVS {/*** CSV导出** @throws Exception*/@Testpublic void exportCsv() throws IOException {String srcCSV = "F:/cnt_programa.csv";String targetFile = "F:/test.csv";CsvReader reader = new CsvReader(srcCSV, ',', Charset.forName("UTF-8"));CsvWriter write =new CsvWriter(targetFile,',',Charset.forName("UTF-8"));//各字段以引号标记write.setForceQualifier(true);//路过表头//r.readHeaders();//逐条读取记录,直至读完String[] header = {};while (reader.readRecord()) {//把头保存起来if (reader.getCurrentRecord()==0){header = reader.getValues();}//获取当前记录位置System.out.print(reader.getCurrentRecord() + ".");//读取一条记录System.out.println(reader.getRawRecord());String[] tmp = {reader.getValues()[0],reader.getValues()[1]};//修改记录,并只写入第一个字段和第二字段if (!header[1].equals(tmp[1]) && ("".equals(tmp[1])||tmp==null)){tmp[1]="空";write.writeRecord(tmp);}else{write.writeRecord(new String[]{reader.getValues()[0],reader.getValues()[1]});}}reader.close();write.close();}}

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"

以上所述是小编给大家介绍的使用Javacsv.jar的jar包操作csv文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章