📜  使用 OpenCSV 在Java中编写 CSV 文件

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

使用 OpenCSV 在Java中编写 CSV 文件

逗号分隔值 (CSV) 文件只是一个普通的纯文本文件,将数据逐列存储,并用分隔符分割(例如,通常是逗号“,”)。

OpenCSV 是一个用于Java的 CSV 解析器库。 OpenCSV 支持您想要执行的所有基本 CSV 类型的操作。 Java 7 目前是 OpenCSV 支持的最低版本。 Java语言不提供任何有效处理 CSV 文件的本地支持,因此我们使用 OpenCSV 来处理Java中的 CSV 文件。

如何在您的项目中添加 OpenCSV?

  • 对于 maven 项目,您可以在 pom.xml 文件中包含 OpenCSV maven 依赖项。
    
        com.opencsv
        opencsv
        4.1
    
    
  • 对于 Gradle 项目,您可以包含 OpenCSV 依赖项。
    compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
  • 您可以下载 OpenCSV Jar 并包含在您的项目类路径中。

    编写 CSV 文件
      编写 CSV 文件就像阅读一样简单。通过将 FileWriter 对象作为参数传递来创建 CSVWriter 的实例,并使用 CSVWriter 类的方法开始将数据写入 CSV 文件。写入数据后,我们需要通过调用 CSVWriter 类的 close() 方法来关闭 CSVWriter 连接。
    1. 逐行写入数据 – CSVWriter 可以使用 writeNext() 方法逐行写入,其中将字符串数组与每个逗号分隔的元素作为单独的条目一起传递。
      代码:
      public static void writeDataLineByLine(String filePath)
      {
          // first create file object for file placed at location
          // specified by filepath
          File file = new File(filePath);
          try {
              // create FileWriter object with file as parameter
              FileWriter outputfile = new FileWriter(file);
        
              // create CSVWriter object filewriter object as parameter
              CSVWriter writer = new CSVWriter(outputfile);
        
              // adding header to csv
              String[] header = { "Name", "Class", "Marks" };
              writer.writeNext(header);
        
              // add data to csv
              String[] data1 = { "Aman", "10", "620" };
              writer.writeNext(data1);
              String[] data2 = { "Suraj", "10", "630" };
              writer.writeNext(data2);
        
              // closing writer connection
              writer.close();
          }
          catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      

      输出:带有以下数据的 result.csv 文件

      "Name", "Class", "Marks"
      "Aman", "10", "620"
      "Suraj", "10", "630"
      
    2. 一次写入所有数据-为了一次读取数据,调用 CSVWriter 类的 writeAll() 方法,并将 String[] 列表作为参数传递,每个 String[] 代表文件的一行。
      代码:
      public static void writeDataAtOnce(String filePath)
      {
        
          // first create file object for file placed at location
          // specified by filepath
          File file = new File(filePath);
        
          try {
              // create FileWriter object with file as parameter
              FileWriter outputfile = new FileWriter(file);
        
              // create CSVWriter object filewriter object as parameter
              CSVWriter writer = new CSVWriter(outputfile);
        
              // create a List which contains String array
              List data = new ArrayList();
              data.add(new String[] { "Name", "Class", "Marks" });
              data.add(new String[] { "Aman", "10", "620" });
              data.add(new String[] { "Suraj", "10", "630" });
              writer.writeAll(data);
        
              // closing writer connection
              writer.close();
          }
          catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      

      输出:带有以下数据的 result.csv 文件

      "Name", "Class", "Marks"
      "Aman", "10", "620"
      "Suraj", "10", "630"
      

    使用不同的分隔符编写 CSV 文件

    默认情况下,CSV 的分隔符是逗号 (, )。如果您想将另一个字符作为分隔符,以便可以将其作为参数传递给 CSVWriter 类。
    Syntax :
    CSVWriter(Writer writer, char separator, char quotechar,
                                  char escapechar, String lineEnd)
    Description : Constructs CSVWriter with supplied separator,
    quote char, escape char and line ending.
    

    代码:

    public static void writeDataForCustomSeparatorCSV(String filePath)
    {
      
        // first create file object for file placed at location
        // specified by filepath
        File file = new File(filePath);
      
        try {
            // create FileWriter object with file as parameter
            FileWriter outputfile = new FileWriter(file);
      
            // create CSVWriter with '|' as separator
            CSVWriter writer = new CSVWriter(outputfile, '|',
                                             CSVWriter.NO_QUOTE_CHARACTER,
                                             CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                             CSVWriter.DEFAULT_LINE_END);
      
            // create a List which contains String array
            List data = new ArrayList();
            data.add(new String[] { "Name", "Class", "Marks" });
            data.add(new String[] { "Aman", "10", "620" });
            data.add(new String[] { "Suraj", "10", "630" });
            writer.writeAll(data);
      
            // closing writer connection
            writer.close();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    输出:带有以下数据的 result.csv 文件

    Name|Class|Marks
    Aman|10|620
    Suraj|10|630
    

    例子:
    让我们创建一个Java程序,它生成一个分号分隔的 csv 文件并包含作为输入提供的数据。

    Input:
    Enter no of rows
    9
    Enter Data
    Name Class Marks
    Aman 10 543
    Amar 10 541
    Sanjeet 10 555
    Luv 10 580
    Ranjeet 10 512
    Rabi 10 540
    Dev 10 333
    Sunny 10 198
    

    代码:

    // Java program to illustrate
    // for Writing Data in CSV file
    import java.io.*;
    import java.util.*;
    import com.opencsv.CSVWriter;
      
    public class ResultGenerator {
        private static final String CSV_FILE_PATH
            = "./result.csv";
        public static void main(String[] args)
        {
            addDataToCSV(CSV_FILE_PATH);
        }
        public static void addDataToCSV(String output)
        {
            // first create file object for file placed at location
            // specified by filepath
            File file = new File(output);
            Scanner sc = new Scanner(System.in);
            try {
                // create FileWriter object with file as parameter
                FileWriter outputfile = new FileWriter(file);
      
                // create CSVWriter with ';' as separator
                CSVWriter writer = new CSVWriter(outputfile, ';',
                                                 CSVWriter.NO_QUOTE_CHARACTER,
                                                 CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                                 CSVWriter.DEFAULT_LINE_END);
      
                // create a List which contains Data
                List data = new ArrayList();
      
                System.out.println("Enter no of rows");
                int noOfRow = Integer.parseInt(sc.nextLine());
                System.out.println("Enter Data");
                for (int i = 0; i < noOfRow; i++) {
                    String row = sc.nextLine();
                    String[] rowdata = row.split(" ");
                    data.add(rowdata);
                }
      
                writer.writeAll(data);
      
                // closing writer connection
                writer.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

    输出:带有以下数据的 result.csv 文件

    Name;Class;Marks
    Aman;10;543
    Amar;10;541
    Sanjeet;10;555
    Luv;10;580
    Ranjeet;10;512
    Rabi;10;540
    Dev;10;333
    Sunny;10;198
    
    

    在以后的文章中,我们将包含更多使用 OpenCSV 对 CSV 文件进行的操作。
    参考: OpenCSV 文档、CSVWriter 类文档