java 语言CSV格式文件的生成

今天和大家分析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生成分析完成,下篇分享文件一般文件生成 问题,敬请期待!

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值