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

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

    thanks for this thread, it has been really useful for me... I've enhanced a little bit the provided solution in order to accept also POJO where some fields are not annotated (not meant to be read/written):

    public class ColumnAndNameMappingStrategy extends ColumnPositionMappingStrategy {
    
    @Override
    public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
    
        super.setColumnMapping(new String[ getAnnotatedFields(bean)]);
        final int numColumns = getAnnotatedFields(bean);
        final int totalFieldNum = findMaxFieldIndex();
        if (!isAnnotationDriven() || numColumns == -1) {
            return super.generateHeader(bean);
        }
    
        String[] header = new String[numColumns];
    
        BeanField beanField;
        for (int i = 0; i <= totalFieldNum; i++) {
            beanField = findField(i);
            if (isFieldAnnotated(beanField.getField())) {
                String columnHeaderName = extractHeaderName(beanField);
                header[i] = columnHeaderName;
            }
        }
        return header;
    }
    
    private int getAnnotatedFields(T bean) {
        return (int) Arrays.stream(FieldUtils.getAllFields(bean.getClass()))
                .filter(this::isFieldAnnotated)
                .count();
    }
    
    private boolean isFieldAnnotated(Field f) {
        return f.isAnnotationPresent(CsvBindByName.class) || f.isAnnotationPresent(CsvCustomBindByName.class);
    }
    
    private String extractHeaderName(final BeanField beanField) {
        if (beanField == null || beanField.getField() == null) {
            return StringUtils.EMPTY;
        }
    
        Field field = beanField.getField();
    
        if (field.getDeclaredAnnotationsByType(CsvBindByName.class).length != 0) {
            final CsvBindByName bindByNameAnnotation = field.getDeclaredAnnotationsByType(CsvBindByName.class)[0];
            return bindByNameAnnotation.column();
        }
    
        if (field.getDeclaredAnnotationsByType(CsvCustomBindByName.class).length != 0) {
            final CsvCustomBindByName bindByNameAnnotation = field.getDeclaredAnnotationsByType(CsvCustomBindByName.class)[0];
            return bindByNameAnnotation.column();
        }
    
        return StringUtils.EMPTY;
    }
    

    }

提交回复
热议问题