📜  使用 OpenCSV 将 CSV 映射到 JavaBeans

📅  最后修改于: 2022-05-13 01:54:53.212000             🧑  作者: Mango

使用 OpenCSV 将 CSV 映射到 JavaBeans

OpenCSV 提供了将 CSV 文件映射到 Java bean 列表的类。 CsvToBean 类用于将 CSV 数据映射到 JavaBeans。 CSV数据可以解析成bean,但需要做的是定义映射策略,并将策略传递给CsvToBean,将数据解析成bean。 HeaderColumnNameTranslateMappingStrategy 是将列 id 映射到Java bean 属性的映射策略。

  1. 首先将 OpenCSV 添加到项目中。
    • 对于 maven 项目,在 pom.xml 文件中包含 OpenCSV maven 依赖项。
      
          com.opencsv
          opencsv
          4.1
      
      
    • 对于 Gradle 项目,包括 OpenCSV 依赖项。
      compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
    • 您可以下载 OpenCSV Jar 并包含在您的项目类路径中。
  2. 将 CSV 映射到 JavaBeans
    将 CSV 映射到 JavaBeans 是一个简单易行的过程。只需遵循以下几个步骤:
    1. 使用列 id 和 bean 属性之间的映射创建一个 Hashmap。
      Map mapping = new HashMap();
              mapping.put("column  id ", "javaBeanProperty");
      

      然后添加 csv 文件的所有列 id 及其对应的 javabean 属性。

    2. 创建 HeaderColumnNameTranslateMappingStrategy 对象将映射 hashmap 传递给 setColumnMapping 方法。
      HeaderColumnNameTranslateMappingStrategy strategy =
       new HeaderColumnNameTranslateMappingStrategy();
              strategy.setType(JavaBeanObject.class);
              strategy.setColumnMapping(mapping);
      
    3. 创建 CSVReade 和 CsvToBean 类的对象
      String csvFilename = "data.csv";
      CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
      CsvToBean csv = new CsvToBean();
      
    4. 调用 CsvToBean 类的 parse 方法并传递 HeaderColumnNameTranslateMappingStrategy 和 CSVReader 对象。
      List list = csv.parse(strategy, csvReader);
      

示例:让我们将包含 Student 数据的 csv 文件转换为具有属性 Name、RollNo、Department、Result、Pointer 的 Student 对象。

StudentData.csv:

name, rollno, department, result, cgpa
amar, 42, cse, pass, 8.6
rohini, 21, ece, fail, 3.2
aman, 23, cse, pass, 8.9
rahul, 45, ee, fail, 4.6
pratik, 65, cse, pass, 7.2
raunak, 23, me, pass, 9.1
suvam, 68, me, pass, 8.2

首先创建一个Student Class,属性为Name、RollNo、Department、Result、Pointer。然后创建一个将 csv 数据映射到 JavaBeans 对象的主类。

程式:

  1. 学生。Java
    public class Student {
        private static final long serialVersionUID = 1L;
      
        public String Name, RollNo, Department, Result, Pointer;
      
        public String getName()
        {
            return Name;
        }
      
        public void setName(String name)
        {
            Name = name;
        }
      
        public String getRollNo()
        {
            return RollNo;
        }
      
        public void setRollNo(String rollNo)
        {
            RollNo = rollNo;
        }
      
        public String getDepartment()
        {
            return Department;
        }
      
        public void setDepartment(String department)
        {
            Department = department;
        }
      
        public String getResult()
        {
            return Result;
        }
      
        public void setResult(String result)
        {
            Result = result;
        }
      
        public String getPointer()
        {
            return Pointer;
        }
      
        public void setPointer(String pointer)
        {
            Pointer = pointer;
        }
      
        @Override
        public String toString()
        {
            return "Student [Name=" + Name + ", RollNo=" + RollNo + ",
                Department
                = " + Department + ",
                Result = " + Result
                         + ", Pointer=" + Pointer + "]";
        }
    }
    
  2. csvtobean。Java
    import java.io.*;
    import java.util.*;
      
    import com.opencsv.CSVReader;
    import com.opencsv.bean.CsvToBean;
    import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;
      
    public class csvtobean {
        public static void main(String[] args)
        {
      
            // Hashmap to map CSV data to 
            // Bean attributes.
            Map mapping = new 
                          HashMap();
            mapping.put("name", "Name");
            mapping.put("rollno", "RollNo");
            mapping.put("department", "Department");
            mapping.put("result", "Result");
            mapping.put("cgpa", "Pointer");
      
            // HeaderColumnNameTranslateMappingStrategy
            // for Student class
            HeaderColumnNameTranslateMappingStrategy strategy =
                 new HeaderColumnNameTranslateMappingStrategy();
            strategy.setType(Student.class);
            strategy.setColumnMapping(mapping);
      
            // Create castobaen and csvreader object
            CSVReader csvReader = null;
            try {
                csvReader = new CSVReader(new FileReader
                ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv"));
            }
            catch (FileNotFoundException e) {
      
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            CsvToBean csvToBean = new CsvToBean();
      
            // call the parse method of CsvToBean
            // pass strategy, csvReader to parse method
            List list = csvToBean.parse(strategy, csvReader);
      
            // print details of Bean object
            for (Student e : list) {
                System.out.println(e);
            }
        }
    }
    

输出

Student [Name=amar, RollNo=42, Department=cse, Result=pass, Pointer=8.6]
Student [Name=rohini, RollNo=21, Department=ece, Result=fail, Pointer=3.2]
Student [Name=aman, RollNo=23, Department=cse, Result=pass, Pointer=8.9]
Student [Name=rahul, RollNo=45, Department=ee, Result=fail, Pointer=4.6]
Student [Name=pratik, RollNo=65, Department=cse, Result=pass, Pointer=7.2]
Student [Name=raunak, RollNo=23, Department=me, Result=pass, Pointer=9.1]
Student [Name=suvam, RollNo=68, Department=me, Result=pass, Pointer=8.2]

参考: OpenCSV 文档、CsvTOBean 文档、MappingStrategy