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


@


一、簡介

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM