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



我想从html页面上传一个CSV文件,然后在java控制器中将其转换为Model Object。

我使用以下方法:

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这样没有空格的字段。但对于像MSGDATA这样有空格的字段,这是失败的。对于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文件中读取标头,所以无法在模型文件中找到它们的setter。在这里,我们的模型类字段的名称可以如下传递:

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

现在,它将能够在模型文件中定位这些头字段的setter,从而将CSV解析到模型文件中。

最新更新