I am trying to use opencsv to parse a csv file like this:
2020-09-18 06:50:00.000000
I am trying to add the parsed data following this tutorial: https://attacomsian.com/blog/spring-boot-upload-parse-csv-file. This is my model:
public class MyIndPrd implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CsvBindByName
private String service;
@CsvBindByName
private OffsetDateTime time;
@CsvBindByName
private Long nbAppels;
@CsvBindByName
private Double tempsDeReponseMoyenMillisecondes;
@CsvBindByName
private Long volume;
@CsvBindByName
private Double tempsDeReponseMoyenSecondes;
}
I try to parse the offsetDateTime
by doing :
OffsetDateTime odt = OffsetDateTime.parse (myIndPrds.get (i) .getTime ());
before recording it
but it doesn't seem like you want to do it
@PostMapping("/upload-csv-file")
public String uplaodCSVFile(@RequestParam("file") MultipartFile file, Model model){
if (file.isEmpty()){
model.addAttribute("message", "Veuillez selectionner un fichier csv à importer.");
model.addAttribute("status", false);
}else try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
// create csv bean reader
CsvToBean<MyIndPrd> csvToBean = new CsvToBeanBuilder(reader)
.withType(MyIndPrd.class)
.withSeparator(';')
.withIgnoreLeadingWhiteSpace(true)
.build();
// convert CsvToBean object
List<MyIndPrd> myIndPrds = csvToBean.parse();
for (int i = 0;i<myIndPrds.size();i++){
OffsetDateTime odt = OffsetDateTime.parse(myIndPrds.get(i).getTime());
MyIndPrd ind = new MyIndPrd();
ind.setService(myIndPrds.get(i).getService());
ind.setTime(odt);
ind.setNbAppels(Long.valueOf(myIndPrds.get(i).getNbAppels()));
ind.setVolume(Long.valueOf(myIndPrds.get(i).getVolume()));
ind.setTempsDeReponseMoyenMillisecondes(Double.valueOf(myIndPrds.get(i).getTempsDeReponseMoyenMillisecondes()));
ind.setTempsDeReponseMoyenSecondes(Double.valueOf(myIndPrds.get(i).getTempsDeReponseMoyenSecondes()));
iMyIndPrdService.saveMyData(ind);
}
model.addAttribute("myIndProdCsv", myIndPrds);
model.addAttribute("status", true);
} catch (Exception ex) {
model.addAttribute("message", "An error occurred while processing the CSV file.");
model.addAttribute("status", false);
}
return "mon-dasboard";
}
Thanks for your help
Your date-time string (e.g.
2020-09-18 06:50:00.000000
as you have mentioned in the question) in the CSV does not have timezone-offset and therefore the most appropriate type to parse it into would beLocalDateTime
.You can define a converter class to convert the date-time string from the CSV into
LocalDateTime
.and then you can annotate the field as
However, if you still want to parse your date-time string into
OffsetDateTime
, here is how you can do it:and then you can annotate the field as
A quick demo of how this parsing works:
If you are using
OpenCSV 5
You do not need to define a converter class. You can simply do it as