I want to upload a CSV file from html page and then in the java controller want to convert it to Model Object.
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 . It is giving error for fields like MSG DATA as follows:
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.