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

后端 未结 19 1492
温柔的废话
温柔的废话 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 05:08

    If you dont have getDeclaredAnnotationsByType method, but need the name of your original field name:

    beanField.getField().getName()

    public class CustomMappingStrategy extends ColumnPositionMappingStrategy {
    @Override
    public String[] generateHeader() {
        final int numColumns = findMaxFieldIndex();
        if (!isAnnotationDriven() || numColumns == -1) {
            return super.generateHeader();
        }
    
        header = new String[numColumns + 1];
    
        BeanField beanField;
        for (int i = 0; i <= numColumns; i++) {
            beanField = findField(i);
            String columnHeaderName = extractHeaderName(beanField);
            header[i] = columnHeaderName;
        }
        return header;
    }
    
    private String extractHeaderName(final BeanField beanField) {
        if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotations().length == 0) {
            return StringUtils.EMPTY;
        }
        return beanField.getField().getName();
    }
    

    }

提交回复
热议问题