简体   繁体   English

上载CSV文件并将其转换为Java模型对象

[英]Uploading a CSV File and converting it to Java Model Object

I want to upload a CSV file from html page and then in the java controller want to convert it to Model Object. 我想从html页面上传CSV文件,然后在java控制器中将其转换为模型对象。

I am using the following approach: 我正在使用以下方法:

ICsvBeanReader beanReader = null;
    try {
        beanReader = new CsvBeanReader(new InputStreamReader(file.getInputStream()),
                CsvPreference.STANDARD_PREFERENCE);

        // the header elements are used to map the values to the bean (names
        // must match)
        final String[] header = beanReader.getHeader(true);
        // get Cell Processor
        final CellProcessor[] processors = getProcessors();

        CSVData csvData;
        while ((csvData = beanReader.read(CSVData.class, header, processors)) != null) {
            System.out.println(csvData);
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }


    private static CellProcessor[] getProcessors() {

    final CellProcessor[] processors = new CellProcessor[] {
            new NotNull(), // CustomerId
            new NotNull(), // CustomerName
            new NotNull(),
            new NotNull(),
            new NotNull(),
            new NotNull(new ParseInt()),
            new NotNull(new ParseInt()),
            new NotNull(new ParseInt()),
            new NotNull(new ParseDouble()),
            new NotNull(),
            new NotNull()



    };
    return processors;
}

This is working for fields having no white spaces like msgID .But it is failing for fields with white spaces like MSG DATA . 这适用于msgID等没有空格的字段,但不适用于MSG DATA等带有空格的字段。 It is giving error for fields like MSG DATA as follows: 它给像MSG DATA这样的字段错误,如下所示:

org.supercsv.exception.SuperCsvReflectionException: unable to find method setMSG DATA(java.lang.String) in class com.springboot.dto.CSVData - check that the corresponding nameMapping element matches the field name in the bean, and the cell processor returns a type compatible with the field context=null

Thanks 谢谢

For making this code work, changes were required to the following piece of code: 为了使此代码有效,需要对以下代码段进行更改:

final String[] header = beanReader.getHeader(true);

Here as it is reading the headers from the csv file so it is not able to find the setters for them in the model file. 此处是从csv文件中读取标头,因此无法在模型文件中找到它们的设置器。 Here the name of our model class fields can be passed as follows: 在这里,我们的模型类字段的名称可以按以下方式传递:

final String[] header = {"msgID" , "msgData" , "dataUnits" ...}

Now it will be able to locate the setters for these header fields in the model file and thus parse the CSV in to the model file. 现在,它将能够在模型文件中找到这些标头字段的设置器,从而将CSV解析到模型文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM