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

后端 未结 19 1508
温柔的废话
温柔的废话 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:58

    Great thread, I don't have any annotations in my pojo and this is how I did based on all the previous answers. Hope it helps others.

    OpenCsv Version: 5.0 List readVendors = getFromMethod(); String[] fields= {"id","recordNumber","finVendorIdTb","finVenTechIdTb","finShortNameTb","finVenName1Tb","finVenName2Tb"};

                String[] csvHeader= {"Id#","Shiv Record Number","Shiv Vendor Id","Shiva Tech Id#","finShortNameTb","finVenName1Tb","finVenName2Tb"};
    
                CustomMappingStrategy mappingStrategy = new CustomMappingStrategy(csvHeader);//csvHeader as per custom header irrespective of pojo field name
                mappingStrategy.setType(FinVendor.class);
                mappingStrategy.setColumnMapping(fields);//pojo mapping fields
    
    
                StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withMappingStrategy(mappingStrategy).build();
                beanToCsv.write(readVendors);
    

    //custom mapping class as mentioned in the thread by many users private static class CustomMappingStrategy extends ColumnPositionMappingStrategy {

                        String[] header;
    
                        public CustomMappingStrategy(String[] cols) {
    
                                header = cols;
                        }
    
                        @Override
                        public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
                            super.generateHeader(bean);
                                return header;
                        }
                        }
    

    Output:

    Id#     Shiv Record Number      Shiv Vendor Id   Fin Tech Id#      finShortNameTb  finVenName1Tb   finVenName2Tb   finVenDefaultLocTb
    1       VEN00053                678             33316025986        THE ssOHIO S_2  THE UNIVERSITY     CHK         Test
    2       VEN02277                1217            3044374205         Fe3 MECHA_1     FR3INC             EFT-1
    3       VEN03118                1310            30234484121        PE333PECTUS_1   PER332CTUS AR      EFT-1       Test
    

提交回复
热议问题