1

我正在尝试使用 opencsv 来解析这样的 csv 文件:

2020-09-18 06:50:00.000000

我正在尝试按照本教程添加解析的数据:https ://attacomsian.com/blog/spring-boot-upload-parse-csv-file 。这是我的模型:

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

我尝试解析 offsetDateTime

通过做 :

OffsetDateTime odt = OffsetDateTime.parse (myIndPrds.get (i) .getTime ());

在录制之前

但你似乎不想这样做

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

谢谢你的帮助

4

1 回答 1

0

您在 CSV 中的日期时间字符串(例如2020-09-18 06:50:00.000000您在问题中提到的)没有时区偏移量,因此将其解析为最合适的类型是LocalDateTime.

您可以定义一个转换器类将日期时间字符串从 CSV 转换为LocalDateTime.

public class LocalDateTimeConverter extends AbstractBeanField {
    @Override
    protected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.n");
        LocalDateTime ldt = LocalDateTime.parse(strDate, dtf);
        return ldt;
    }
}

然后您可以将该字段注释为

@CsvBindByName(converter = LocalDateTimeConverter.class)
private LocalDateTime time;

但是,如果您仍想将日期时间字符串解析为OffsetDateTime,请执行以下操作:

public class OffsetDateTimeConverter extends AbstractBeanField {
    @Override
    protected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.n").withZone(ZoneId.systemDefault());
        ZonedDateTime zdt = ZonedDateTime.parse(strDate, dtf);
        OffsetDateTime odt = zdt.toOffsetDateTime();
        return odt
    }
}

然后您可以将该字段注释为

@CsvBindByName(converter = OffsetDateTimeConverter.class)
private OffsetDateTime time;

这个解析如何工作的快速演示:

import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDate = "2020-09-18 06:50:00.000000";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.n").withZone(ZoneId.systemDefault());
        ZonedDateTime zdt = ZonedDateTime.parse(strDate, dtf);
        OffsetDateTime odt = zdt.toOffsetDateTime();
        System.out.println(zdt);
        System.out.println(odt);
    }
}

如果您正在使用OpenCSV 5

您不需要定义转换器类。你可以简单地这样做

@CsvDate(value = "uuuu-MM-dd HH:mm:ss.n")
@CsvBindByName
private LocalDateTime time;
于 2020-12-01T10:50:43.360 回答