OpenCsv writes wrong column names with BeanToCsv + HeaderColumnNameTranslateMappingStrategy

后端 未结 2 1654
梦毁少年i
梦毁少年i 2020-12-19 08:10

I\'m using opencsv 3.6 in order to create a csv file starting from a java bean.

First of all, I tried this code:

import com.opencsv.CSVR         


        
2条回答
  •  Happy的楠姐
    2020-12-19 08:53

    I have been using openCSV for five years now and I am still learning stuff about it. The issue is that the HeaderColumnNameMappingStrategy and HeaderColumnNameTranslateMappingStrategy were made for the CsvToBean. It wants a file to read to get the header out to see where the reader should read from.

    For the BeanToCsv class use the ColumnPositionMappingStrategy class. You give it the class you are mapping and a list of the columns you want to map and it does the rest for you.

    Here is a little test method I wrote that worked.

    public void createUsingBeanToCsv(int numRecords, FileWriter fos) {
        List smallRecords = new ArrayList<>(numRecords);
        for (int i = 0; i < numRecords; i++) {
            smallRecords.add(SmallRecordGenerator.createRecord(i));
        }
    
        BeanToCsv beanToCsv = new BeanToCsv<>();
        ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy<>();
        strategy.setType(SmallRecord.class);
        String[] columns = new String[]{"bigDecimal_1", "name_1", "intNumber_1"};
        strategy.setColumnMapping(columns);
    
        beanToCsv.write(strategy, fos, smallRecords);
    
    }
    

提交回复
热议问题