First, give the tool class
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/ * * *@author: hj
 * @date: in the 2021-01-21 s when *@description: Csv parsing tool class **/
@Slf4j
public class CsvUtil {

    /** * Use ColumnPositionMapping to resolve **@param file
     * @param clazz
     * @param <T>
     * @return* /
    public static <T> List<T> getCsvData(MultipartFile file, Class<T> clazz) {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("Reading CSV file failed!");
        }
        // Adopt the position-based policy
        ColumnPositionMappingStrategy<T> strategy = new ColumnPositionMappingStrategy<>();
        strategy.setType(clazz);
        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in)
                .withSeparator(', ')// Specify the delimiter
                .withQuoteChar('\' ')// Specify a reference character
                .withSkipLines(1)// Skip the first line
                .withMappingStrategy(strategy)// Specify a policy
            	.build();
        returncsvToBean.parse(); }}Copy the code
Second, for the use of this tool class

ColumnPositionMappingStrategy strategy

  1. The CSV file
Date, Low-rated bond spreads, CSI 300 2020/12/23,0.666666,66 2020/12/22,0.111111,11 2020/12/21,1.222222,22 2020/12/18,1.333333,33Copy the code
  1. Annotation based on @csvBindbyPosition
     // Here is a custom string to date ConverterToDate, so use @csvCustomBindbyPosition annotation
    @CsvCustomBindByPosition(position = 0, converter = ConverterToDate.class)
    private Date dateTime;

    @CsvBindByPosition(position = 1)
    private BigDecimal emotionalFactorValue;

    @CsvBindByPosition(position = 2)
    private BigDecimal stockIndexValue;
Copy the code
  1. Custom Converter
import com.opencsv.bean.AbstractBeanField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/ * * *@author: hj
 * @date: the 2021-01-21 times *@description: string to date **/
@Slf4j
public class ConverterToDate extends AbstractBeanField {
    @Override
    protected Date convert(String value) {
        Date date = new Date();
        if (StringUtils.isBlank(value)) {
            return date;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
            date = format.parse(value);
        } catch (ParseException e) {
            log.error("Error converting string to date type");
            e.printStackTrace();
        }
        returndate; }}Copy the code