OpenCSV: How to create CSV file from POJO with custom column headers and custom column positions?

后端 未结 19 1460
温柔的废话
温柔的废话 2020-12-08 04:14

I have created a MappingsBean class where all the columns of the CSV file are specified. Next I parse XML files and create a list of mappingbeans. Then I write that data int

19条回答
  •  一整个雨季
    2020-12-08 04:51

    This can be done using a HeaderColumnNameMappingStrategy along with a custom Comparator as well. Which is recommended by the official doc http://opencsv.sourceforge.net/#mapping_strategies

        File reportFile = new File(reportOutputDir + "/" + REPORT_FILENAME);
        Writer writer = new PrintWriter(reportFile);
        
    final List order = List.of("TradeID", "GWML GUID", "MXML GUID", "GWML File", "MxML File", "MxML Counterparty", "GWML Counterparty");
        final FixedOrderComparator comparator = new FixedOrderComparator(order);
        HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(MappingsBean.class);
        strategy.setColumnOrderOnWrite(comparator);
    
        StatefulBeanToCsv beanToCsv = new
          StatefulBeanToCsvBuilder(writer)
          .withMappingStrategy(strategy)
          .build();
        beanToCsv.write(makeFinalMappingBeanList());
        writer.close();
    

提交回复
热议问题