📜  使用 OpenCSV 将Java Bean 映射到 CSV

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

使用 OpenCSV 将Java Bean 映射到 CSV

将Java Bean(对象)转换为 CSV 文件的需求非常普遍,有很多方法可以将 Bean 写入 CSV 文件,但将Java Bean 映射到 CSV 的最佳方法之一是使用 OpenCSV 库。在 OpenCSV 中有一个类名StatefulBeanToCsvBuilder ,它有助于将Java Bean 转换为 CSV。

  1. 第一个任务是将 OpenCSV 库添加到 Project中。
    • 对于 maven 项目,在 pom.xml 文件中包含 OpenCSV maven 依赖项。
      
          com.opencsv
          opencsv
          4.1
      
      
    • 对于 Gradle 项目,包括 OpenCSV 依赖项。
      compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
    • 您可以下载 OpenCSV Jar 并包含在您的项目类路径中。
  2. 将 JavaBean 映射到 CSV
    以下是将Java Bean 映射到 CSV 的分步过程。
    1. 创建用于将数据写入 CSV 文件的 Writer 实例。
      Writer writer = Files.newBufferedWriter(Paths.get(file_location));
    2. 创建需要写入 CSV 文件的对象列表。
    3. 使用 ColumnPositionMappingStrategy 将 Created 对象的列映射到 csv 的列。
      这是一个可选步骤。如果不使用 ColumnPositionMappingStrategy,那么对象将被写入 csv,其列名与对象的属性名相同。
      ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
          mappingStrategy.setType(Employee.class);
      
      where Employee is the object to be mapped with CSV.
      
    4. 创建StatefulBeanToCsvBuilder后,调用StatefulBeanToCsvBuilder类的build方法创建StatefulBeanToCsv类的对象,以writer对象为参数。用户还可以根据需要提供:
      • ColumnPositionMappingStrategy借助 StatefulBeanToCsvBuilder 对象的withMappingStrategy函数。
      • 借助StatefulBeanToCsvBuilder对象的withSeparator函数生成的 csv 文件的分隔符。
      • 借助StatefulBeanToCsvBuilder对象的withQuotechar函数生成 csv 文件的withQuotechar
      StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
      .withMappingStrategy(mappingStrategy)
      . withSeparator('#')
                          .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                          .build();
      
    5. 创建 StatefulBeanToCsv 类的对象后,您可以借助 StatefulBeanToCsv 对象的 write 方法将对象或对象列表添加到 csv 文件中。
      beanToCsv.write(Employeelist);
      

示例:在此示例中,我们将创建具有名称、年龄、公司、工资等属性的 Employee 对象列表。然后我们将生成一个包含 Employee 对象的 CSV 文件Employees.csv。
代码:

  1. 员工。Java
    public class Employee {
      
        public String Name, Age, Company, Salary;
      
        public Employee(String name, String age, 
                    String company, String salary)
        {
            super();
            Name = name;
            Age = age;
            Company = company;
            Salary = salary;
        }
      
        @Override
        public String toString()
        {
           return "Employee [Name=" + Name + ", 
           Age=" + Age + ", Company=" + Company + ", 
           Salary=" + Salary + "]";
        }
    }
    
  2. BeanToCSV。Java
    import java.io.FileWriter;
    import java.io.Writer;
    import java.nio.*;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.*;
    import com.opencsv.bean.ColumnPositionMappingStrategy;
    import com.opencsv.bean.StatefulBeanToCsv;
    import com.opencsv.bean.StatefulBeanToCsvBuilder;
      
    public class BeanToCSV {
        public static void main(String[] args)
        {
      
            // name of generated csv
            final String CSV_LOCATION = "Employees.csv ";
      
            try {
      
                // Creating writer class to generate
                // csv file
                FileWriter writer = new 
                           FileWriter(CSV_LOCATION);
      
                // create a list of employee
                List EmployeeList = new 
                                     ArrayList();
                Employee emp1 = new Employee
                         ("Mahafuj", "24", "HTc", "75000");
                Employee emp2 = new Employee
                      ("Aman", "24", "microsoft", "79000");
                Employee emp3 = new Employee
                        ("Suvradip", "26", "tcs", "39000");
                Employee emp4 = new Employee
                         ("Riya", "22", "NgGear", "15000");
                Employee emp5 = new Employee
                        ("Prakash", "29", "Sath", "51000");
                EmployeeList.add(emp1);
                EmployeeList.add(emp2);
                EmployeeList.add(emp3);
                EmployeeList.add(emp4);
                EmployeeList.add(emp5);
      
                // Create Mapping Strategy to arrange the 
                // column name in order
                ColumnPositionMappingStrategy mappingStrategy=
                            new ColumnPositionMappingStrategy();
                mappingStrategy.setType(Employee.class);
      
                // Arrange column name as provided in below array.
                String[] columns = new String[] 
                        { "Name", "Age", "Company", "Salary" };
                mappingStrategy.setColumnMapping(columns);
      
                // Creating StatefulBeanToCsv object
                StatefulBeanToCsvBuilder builder=
                            new StatefulBeanToCsvBuilder(writer);
                StatefulBeanToCsv beanWriter = 
              builder.withMappingStrategy(mappingStrategy).build();
      
                // Write list to StatefulBeanToCsv object
                beanWriter.write(EmployeeList);
      
                // closing the writer object
                writer.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

输出

EmployeeData.csv
CSV file contains:-----

"Mahafuj", "24", "HTc", "75000"
"Aman", "24", "microsoft", "79000"
"Suvradip", "26", "tcs", "39000"
"Riya", "22", "NgGear", "15000"
"Prakash", "29", "Sath", "51000"

参考: BeanToCsv 官方文档