繁体   English   中英

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

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

我想从html页面上传CSV文件,然后在java控制器中将其转换为模型对象。

我正在使用以下方法:

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;
}

这适用于msgID等没有空格的字段,但不适用于MSG DATA等带有空格的字段。 它给像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

谢谢

为了使此代码有效,需要对以下代码段进行更改:

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

此处是从csv文件中读取标头,因此无法在模型文件中找到它们的设置器。 在这里,我们的模型类字段的名称可以按以下方式传递:

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

现在,它将能够在模型文件中找到这些标头字段的设置器,从而将CSV解析到模型文件中。

暂无
暂无

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

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