当前位置:   article > 正文

利用opencsv解析csv文件并转化为bean对象_opencsv读取csv转bean

opencsv读取csv转bean

依赖
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>4.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
csv解析工具类
package com.zzx.test.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import cn.hutool.core.io.BOMInputStream;
import com.aliyun.bizworks.bizworkstestcenter.test.testcases.commoditycenter.SkuServiceTest;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: CsvUtils
 * @author: zhouzhxu
 * @description:
 * @data: 2021/11/16 下午2:49 PM
 */
public class CsvUtils {

    public static final Logger logger = LoggerFactory.getLogger(CsvUtils.class);
    private static final String CSV_LOWER = "csv";
    private static final String CSV = "CSV";

    public static <T> List<T> getCsvData(MultipartFile file, Class<T> clazz) throws IOException {
        checkFile(file);
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(new BOMInputStream(file.getInputStream()), "utf-8");
        } catch (Exception e) {
            logger.error("读取csv文件失败!");
        }

        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(clazz);

        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in)
            .withSeparator(',')
            .withMappingStrategy(strategy)
            .build();
        return csvToBean.parse();
    }

    public static void checkFile(MultipartFile file) throws IOException {
        // 判断文件是否存在
        if (null == file) {
            throw new FileNotFoundException("文件不存在");
        }
        // 获得文件名
        String fileName = file.getOriginalFilename();
        // 判断文件是否是csv文件
        if (!fileName.endsWith(CSV_LOWER) && !fileName.endsWith(CSV)) {
            throw new IOException(fileName + "不是csv文件");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
String转Date
public class StringToDate extends AbstractBeanField<Date> {

    @Override
    protected Date convert(String s) throws CsvDataTypeMismatchException,
        CsvConstraintViolationException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date =null;
        try {
            date = format.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("解析错误");
        }
        return date;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
csv对应的bean对象
package com.zzx.test.bean;

import java.util.Date;

import com.opencsv.bean.CsvBindByName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: DataTypeAndCsv
 * @author: zhouzhxu
 * @description:
 * @data: 2021/11/17 上午9:46 PM
 */
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
public class DataAndTypeCsv {

    @CsvBindByName(column = "姓名")
    private String name;

    @CsvBindByName(column = "年龄")
    private Integer age;

    @CsvBindByName(column = "班级")
    private String clazz;

    @CsvCustomBindByName(column = "日期",converter = StringToDate.class)
    private String time;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
测试
package com.zzx.test;

import java.util.List;

import com.zzx.test.util.CsvUtils;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: TestCsv
 * @author: zhouzhxu
 * @description:
 * @data: 2021/11/17 上午9:53 PM
 */
public class TestCsv {
    public static void main(String[] args) {
        String filePath = "/Users/zhouzhxu/Desktop/test.csv";

        List<DataAndTypeCsv> csvData = CsvUtils.getCsvData(filePath, DataAndTypeCsv.class);

        csvData.forEach(dataAndTypeCsv -> System.out.println(dataAndTypeCsv.toString()));
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/148421
推荐阅读
相关标签
  

闽ICP备14008679号