Using CsvBeanReader to read a CSV file with a variable number of columns

前端 未结 3 1055
甜味超标
甜味超标 2020-12-04 01:55

So I\'m working on parsing a .csv file. I took the advice of another thread somewhere on StackOverflow and downloaded SuperCSV. I finally got pretty much everything working,

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 02:29

    Using uniVocity-parsers you can map CSV files with a varying number of columns to java beans. Using annotations:

    class TestBean {
    
    // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
    @NullString(nulls = { "?", "-" })
    // if a value resolves to null, it will be converted to the String "0".
    @Parsed(defaultNullRead = "0")
    private Integer quantity;   // The attribute type defines which conversion will be executed when processing the value.
    // In this case, IntegerConversion will be used.
    // The attribute name will be matched against the column header in the file automatically.
    
    @Trim
    @LowerCase
    // the value for the comments attribute is in the column at index 4 (0 is the first column, so this means fifth column in the file)
    @Parsed(index = 4)
    private String comments;
    
    // you can also explicitly give the name of a column in the file.
    @Parsed(field = "amount")
    private BigDecimal amount;
    
    @Trim
    @LowerCase
    // values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true
    @BooleanString(falseStrings = { "no", "n", "null" }, trueStrings = { "yes", "y" })
    @Parsed
    private Boolean pending;
    ...
    }
    

    To parse your CSV into a list of TestBean instances:

    // BeanListProcessor converts each parsed row to an instance of a given class, then stores each instance into a list.
    BeanListProcessor rowProcessor = new BeanListProcessor(TestBean.class);
    CsvParserSettings parserSettings = new CsvParserSettings();
    parserSettings.setRowProcessor(rowProcessor);
    //Uses the first valid row of the CSV to assign names to each column
    parserSettings.setHeaderExtractionEnabled(true);
    
    CsvParser parser = new CsvParser(parserSettings);
    parser.parse(new FileReader(yourFile));
    
    // The BeanListProcessor provides a list of objects extracted from the input.
    List beans = rowProcessor.getBeans();
    

    Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

提交回复
热议问题