今天和大家分析java 语言CSV格式文件的生成:
此文件格式类似excel,但是比excel生成简单、易用,
1、首先引入jar:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.6</version>
</dependency>
2、工具类代码:
// 写CSV格式文件,data参数可以是字符串等格式,此处处理遍历换行问题
public static int writeCSVFile(String filePathName,List<JSONObject> data) {
log.info("开始写文件:{}",filePathName);
if (CollectionUtils.isEmpty(data)) {
log.info("文件内容为空");
return 0;
}
CSVPrinter csvPrinter = null;
File file = new File(filePathName);
// 获取json key作为csv表头
Object[] headers = data.get(0).keySet().toArray();
try {
CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\r\n")
.withQuoteMode(QuoteMode.ALL).withNullString("");//
OutputStreamWriter mlFileWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8.toString());
csvPrinter = new CSVPrinter(mlFileWriter, csvFormat);
csvPrinter.printRecord(headers);
for(JSONObject jsondata : data){
csvPrinter.printRecord(jsondata.values());
}
} catch (IOException e) {
log.error("异常", e);
throw new RuntimeException("文件创建失败", e);
}finally {
try {
csvPrinter.flush();
csvPrinter.close();
}catch (Exception e) {
log.error("关闭文件流错误", e);
}
}
return 0;
}
3、main方法测试:
public static void main(String[] args) {
writeCSVFile();
}
private static String writeCSVFile(){
String NEW_LINE_SEPARATOR = "\r\n";
// List<JSONObject> data = new ArrayList<>();
CabkeInfi cabkeInf = new CabkeInfi();
cabkeInf.setAttribute("nan");
cabkeInf.setName("si");
CabkeInfi cabkeInfi = new CabkeInfi();
cabkeInfi.setAttribute("nandao");
cabkeInfi.setName("lisi");
List<CabkeInfi> list = new ArrayList<>();
list.add(cabkeInf);
list.add(cabkeInfi);
// JSON.t
// JSONArray json = JSONArray.fromObject(list);
// String str = json.toString();//把json转换为String
String s = JSON.toJSONString(list, SerializerFeature.WriteMapNullValue);
String sQuoteFieldNames = JSON.toJSONString(list, SerializerFeature.QuoteFieldNames);
String UseSingleQuotes = JSON.toJSONString(list, SerializerFeature.UseSingleQuotes);
log.info("字符串打印:{}",s);
log.info("字符串打印:{}",sQuoteFieldNames);
log.info("字符串打印:{}",UseSingleQuotes);
List<JSONObject> data = JSONObject.parseArray(s,JSONObject.class);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(cabkeInf);
JSONObject jsonObjec = (JSONObject) JSONObject.toJSON(cabkeInfi);
// data.add(jsonObjec);
// data.add(jsonObject);
//data =new ArrayList<JSONObject> (JSONObject.t);
if (CollectionUtils.isEmpty(data)) {
return null;
}
CSVPrinter csvPrinter = null;
// String filePathName =null;
String filePathName = "E:\\日常工作\\项目\\"+"RDnandaoCSV";//测试地址
filePathName = filePathName + ".csv";
File file = new File(filePathName);
// 获取json key作为csv表头
Object[] headers = data.get(0).keySet().toArray();
try {
CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR)
.withQuoteMode(QuoteMode.ALL).withNullString("");
OutputStreamWriter mlFileWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8.toString());
csvPrinter = new CSVPrinter(mlFileWriter, csvFormat);
csvPrinter.printRecord(headers);
for(JSONObject jsondata : data){
csvPrinter.printRecord(jsondata.values());
}
} catch (IOException e) {
log.error("异常", e);
throw new RuntimeException("文件创建失败", e);
}finally {
try {
csvPrinter.flush();
csvPrinter.close();
}catch (Exception e) {
log.error("关闭文件流错误", e);
}
}
return filePathName;
}
4、执行完生成这样的文件,打开后如下:
RDnandaoCSV.csv 文件打开
到此CSV生成分析完成,下篇分享文件一般文件生成 问题,敬请期待!