java csv 导出_Java导出CSV

该篇博客介绍了如何在Java中使用Apache Commons CSV库来导出CSV文件。首先引入了1.3版本的库,然后提供了一个方法,根据操作系统类型创建文件路径,并创建CSV文件。方法设置标题和内容,通过CSVPrinter将数据写入文件,避免中文乱码问题。最后,博主指出稍作修改,此方法即可用于动态生成CSV文件。
摘要由CSDN通过智能技术生成

Java导出CSV

使用jar包为

a891be8d92227aa3e7dfb225ddb9378e.png

maven坐标,我用的是1.3,现在已经有1.8了。

org.apache.commons

commons-csv

1.3

Java代码

/**

* 获取系统类型

* @return

*/

public static String getOsName() {

return System.getProperty("os.name");

}

/**

* 返回文件名

* @param excelUnit

* @param name

* @return

*/

public static String exportCsvToFile(String name) {

String osName = getOsName();

String pathPrefix = "";

if (osName.startsWith("Windows")) {

File file=new File("C:\\logFile");

if(!file.exists()){

file.mkdir();

}

pathPrefix = "C:\\logFile\\";

} else {

File file=new File("/usr/apache-tomcat-6.0.44/workdata/logFile");

if(!file.exists()){

file.mkdir();

}

pathPrefix = "/usr/apache-tomcat-6.0.44/workdata/logFile/";

}

String fileChName = pathPrefix + name + ".csv";

BufferedWriter bufferedWriter = null;

FileOutputStream out = null;

try {

out = new FileOutputStream(fileChName);

// 避免中文乱码

byte[] bytes = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};

out.write(bytes);

bufferedWriter = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));

// 设置第一行标题

String[] titleNames = new String[]{"时间","用户","来源","操作类型", "内容","操作IP"};

CSVFormat csvFormat = CSVFormat.EXCEL.withHeader(titleNames);

// 设置内容输出目标

CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, csvFormat);

// 输出数据

String[] contents = new String[]{"时间xx","用户xx","来源xx","操作类型xx", "内容xx","操作IPxx"};

List cellValueList = new ArrayList<>();

cellValueList.add(contents);

for (int i = 0; i < cellValueList.size(); i++) {

csvPrinter.printRecord(cellValueList.get(i));

}

return fileChName;

} catch (Exception e) {

e.printStackTrace();

return null;

} finally {

try {

bufferedWriter.flush();

} catch (Exception e){

e.printStackTrace();

}

try {

bufferedWriter.close();

} catch (Exception e){

e.printStackTrace();

}

try {

out.close();

} catch (Exception e){

e.printStackTrace();

}

}

}

稍微改动以上代码,标题和内容传入这个方法,就可以使用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值