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

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

    CustomMappingStrategy for generic class.

    public class CustomMappingStrategy extends ColumnPositionMappingStrategy {
       @Override
       public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
    
           super.setColumnMapping(new String[ FieldUtils.getAllFields(bean.getClass()).length]);
           final int numColumns = findMaxFieldIndex();
           if (!isAnnotationDriven() || numColumns == -1) {
               return super.generateHeader(bean);
           }
    
           String[] 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().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
               return StringUtils.EMPTY;
           }
    
           final CsvBindByName bindByNameAnnotation = beanField.getField()
                   .getDeclaredAnnotationsByType(CsvBindByName.class)[0];
           return bindByNameAnnotation.column();
       }
    }
    

    POJO Class

     public class Customer{
    
         @CsvBindByPosition(position=1)
         @CsvBindByName(column="CUSTOMER", required = true)
         private String customer;
    }
    

    Client Class

     List data = getEmployeeRecord();
    CustomMappingStrategy custom = new CustomMappingStrategy();
    custom.setType(Employee.class);
    StatefulBeanToCsv writer = new StatefulBeanToCsvBuilder(response.getWriter())
                    .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                    .withSeparator('|')
                    .withOrderedResults(false)
                    .withMappingStrategy(custom)
                    .build();
            writer.write(reportData);
    

提交回复
热议问题