java csv 生成_java实现CSV生成

java实现导出csv功能,首先引入maven依赖:

org.apache.commons

commons-csv

1.6

然后看代码:

/**

* @param filePath 文件路径

* @param list 数据集合

* @param header 表头

*/

public static void write(String filePath,List> list,String... header) {

try {

FileOutputStream fos = new FileOutputStream(filePath);

OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");

CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header);

CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);

//跟上面两行代码是一样的

//CSVPrinter csvPrinter = CSVFormat.DEFAULT.withHeader(header).print(osw);

for (Map map : list) {

csvPrinter.printRecord(map.values());

}

csvPrinter.flush();

csvPrinter.close();

} catch (IOException e) {

e.printStackTrace();

}

}

如果是分多次写入csv,那么可能每个文件的第一次写入需要重新格式化文件写入,后续就进行追加:

/**

* @param filePath 文件路径

* @param list 数据集合

* @param i 第几次写入

* @param header 表头

*/

public static void writeAppend(String filePath,List> list,int i,String... header) {

try {

FileOutputStream fos = null;

if (i>0) {

//追加数据

fos = new FileOutputStream(filePath,true);

}else {

//重新写入

fos = new FileOutputStream(filePath,false);

}

OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");

CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header);

CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);

//跟上面两行代码是一样的

//CSVPrinter csvPrinter = CSVFormat.DEFAULT.withHeader(header).print(osw);

for (Map map : list) {

csvPrinter.printRecord(map.values());

}

csvPrinter.flush();

csvPrinter.close();

} catch (IOException e) {

e.printStackTrace();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值