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

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

    The following works for me to map a POJO to a CSV file with custom column positioning and custom column headers (tested with opencsv-5.0) :

    public class CustomBeanToCSVMappingStrategy extends ColumnPositionMappingStrategy {
    
        @Override
        public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
    
            String[] headersAsPerFieldName = getFieldMap().generateHeader(bean); // header name based on field name
    
            String[] header = new String[headersAsPerFieldName.length];
    
            for (int i = 0; i <= headersAsPerFieldName.length - 1; i++) {
    
                BeanField beanField = findField(i);
    
                String columnHeaderName = extractHeaderName(beanField); // header name based on @CsvBindByName annotation
    
                if (columnHeaderName.isEmpty()) // No @CsvBindByName is present
                    columnHeaderName = headersAsPerFieldName[i]; // defaults to header name based on field name
    
                header[i] = columnHeaderName;
            }
    
            headerIndex.initializeHeaderIndex(header);
    
            return header;
        }
    
        private String extractHeaderName(final BeanField beanField) {
            if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
                return StringUtils.EMPTY;
            }
    
            final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
            return bindByNameAnnotation.column();
        }
    }
    

    Pojo

    Column Positioning in the generated CSV file:

    • The column positioing in the generated CSV file will be as per the annotation @CsvBindByPosition

    Header name in the generated CSV file:

    • If the field has @CsvBindByName, the generated header will be as per the annonation
    • If the field doesn't have @CsvBindByName, then the generated header will be as per the field name

      @Getter @Setter @ToString
      public class Pojo {
      
          @CsvBindByName(column="Voucher Series") // header: "Voucher Series"
          @CsvBindByPosition(position=0)
          private String voucherSeries;
      
          @CsvBindByPosition(position=1) // header: "salePurchaseType"
          private String salePurchaseType;
      }
      

    Using the above Custom Mapping Strategy:

    CustomBeanToCSVMappingStrategy mappingStrategy = new CustomBeanToCSVMappingStrategy<>();
                mappingStrategy.setType(Pojo.class);
    
    StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
                        .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
                        .withMappingStrategy(mappingStrategy)
                        .build();
    
    beanToCsv.write(pojoList);
    

提交回复
热议问题