java解析CSV文件三种方法(openCSV)

3 篇文章 0 订阅

一、简介

1、pom.xml

<!-- csv文件解析依赖 -->
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.4</version>
</dependency>

二、手动解析CSV文件

    //	析csv文件并转成bean(方法一)
    public static List<CsvFile> getCsvDataMethod1(MultipartFile file) {
        ArrayList<CsvFile> csvFileList = new ArrayList<>();

        InputStreamReader in = null;
        String s = null;
        try {
            in = new InputStreamReader(file.getInputStream(), "utf-8");
            BufferedReader bufferedReader = new BufferedReader(in);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                String[] split = line.split(",");
                CsvFile csvFile = new CsvFile();
                csvFile.setName(splitResult(split[0]));
                csvFile.setTitle(splitResult(split[1]));
                csvFile.setNumber(splitResult(split[2]));
                csvFile.setType(splitResult(split[3]));
                csvFile.setPersonnel(splitResult(split[4]));
                csvFile.setTime(splitResult(split[5]));
                csvFileList.add(csvFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvFileList;
    }

去重引号""


    private static String splitResult(String once) {
        String result = "";
        for (int i = 0; i < once.length(); i++) {
            if (once.charAt(i) != '"') {
                result += once.charAt(i);
            }
        }
        return result;
    }

三、openCSV解析CSV文件

    /**
     * 解析csv文件并转成bean(方法二)
     *
     * @param file csv文件
     * @return 数组
     */
    public static List<String[]> getCsvDataMethod2(MultipartFile file) {

        List<String[]> list = new ArrayList<String[]>();
        int i = 0;
        try {
            CSVReader csvReader = new CSVReaderBuilder(
                    new BufferedReader(
                            new InputStreamReader(file.getInputStream(), "utf-8"))).build();
            Iterator<String[]> iterator = csvReader.iterator();
            while (iterator.hasNext()) {
                String[] next = iterator.next();
                //去除第一行的表头,从第二行开始
                if (i >= 1) {
                    list.add(next);
                }
                i++;
            }
            return list;
        } catch (Exception e) {
            System.out.println("CSV文件读取异常");
            return list;
        }
    }

四、openCSV解析CSV文件(结果为实体类)

工具类:

    /**
     * 解析csv文件并转成bean(方法三)
     *
     * @param file  csv文件
     * @param clazz 类
     * @param <T>   泛型
     * @return 泛型bean集合
     */
    public static <T> List<T> getCsvDataMethod3(MultipartFile file, Class<T> clazz) {
        InputStreamReader in = null;
        CsvToBean<T> csvToBean = null;
        try {
            in = new InputStreamReader(file.getInputStream(), "utf-8");
            HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(clazz);
            csvToBean = new CsvToBeanBuilder<T>(in).withMappingStrategy(strategy).build();
        } catch (Exception e) {
            logger.error("数据转化失败");
            return null;
        }
        return csvToBean.parse();
    }

 实体类:

import com.opencsv.bean.CsvBindByName;
import lombok.Data;

@Data
public class CsvFile {

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

    @CsvBindByName(column = "title")
    private String title;

    @CsvBindByName(column = "number")
    private String number;

    @CsvBindByName(column = "type")
    private String type;

    @CsvBindByName(column = "personnel")
    private String personnel;

    @CsvBindByName(column = "time")
    private String time;
}

五、整理完成的CsvUtils

import com.lydms.testopencsv.domain.CsvFile;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class CsvUtils {
    private static final Logger logger = LogManager.getLogger(CsvUtils.class);


    /**
     * 解析csv文件并转成bean(方法二)
     *
     * @param file csv文件
     * @return 数组
     */
    public static List<String[]> getCsvDataMethod2(MultipartFile file) {

        List<String[]> list = new ArrayList<String[]>();
        int i = 0;
        try {
            CSVReader csvReader = new CSVReaderBuilder(
                    new BufferedReader(
                            new InputStreamReader(file.getInputStream(), "utf-8"))).build();
            Iterator<String[]> iterator = csvReader.iterator();
            while (iterator.hasNext()) {
                String[] next = iterator.next();
                //去除第一行的表头,从第二行开始
                if (i >= 1) {
                    list.add(next);
                }
                i++;
            }
            return list;
        } catch (Exception e) {
            System.out.println("CSV文件读取异常");
            return list;
        }
    }


    /**
     * 解析csv文件并转成bean(方法三)
     *
     * @param file  csv文件
     * @param clazz 类
     * @param <T>   泛型
     * @return 泛型bean集合
     */
    public static <T> List<T> getCsvDataMethod3(MultipartFile file, Class<T> clazz) {
        InputStreamReader in = null;
        CsvToBean<T> csvToBean = null;
        try {
            in = new InputStreamReader(file.getInputStream(), "utf-8");
            HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(clazz);
            csvToBean = new CsvToBeanBuilder<T>(in).withMappingStrategy(strategy).build();
        } catch (Exception e) {
            logger.error("数据转化失败");
            return null;
        }
        return csvToBean.parse();
    }


    /**
     * 解析csv文件并转成bean(方法一)
     *
     * @param file
     * @return
     */
    public static List<CsvFile> getCsvDataMethod1(MultipartFile file) {
        ArrayList<CsvFile> csvFileList = new ArrayList<>();

        InputStreamReader in = null;
        String s = null;
        try {
            in = new InputStreamReader(file.getInputStream(), "utf-8");
            BufferedReader bufferedReader = new BufferedReader(in);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                String[] split = line.split(",");
                CsvFile csvFile = new CsvFile();
                csvFile.setName(splitResult(split[0]));
                csvFile.setTitle(splitResult(split[1]));
                csvFile.setNumber(splitResult(split[2]));
                csvFile.setType(splitResult(split[3]));
                csvFile.setPersonnel(splitResult(split[4]));
                csvFile.setTime(splitResult(split[5]));
                csvFileList.add(csvFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvFileList;
    }

    private static String splitResult(String once) {
        String result = "";
        for (int i = 0; i < once.length(); i++) {
            if (once.charAt(i) != '"') {
                result += once.charAt(i);
            }
        }
        return result;
    }
}

 六、相关地址

参考地址:https://www.cnblogs.com/xhj99/p/13536465.html

 git地址:https://github.com/li395092734/test-opencsv

 csv地址:https://files.cnblogs.com/files/blogs/604830/csvfile.zip

 

 

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Knight-Key

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值