簡體   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